/**
 * Production Secret Validation
 * Ensures required secrets are set in production
 */

import { logger } from './logger'

interface SecretConfig {
  name: string
  envVar: string
  required: boolean
  defaultValue?: string
  isProductionOnly?: boolean
}

const requiredSecrets: SecretConfig[] = [
  {
    name: 'JWT Secret',
    envVar: 'JWT_SECRET',
    required: true,
    defaultValue: 'your-secret-key-change-in-production',
    isProductionOnly: true,
  },
  {
    name: 'Database Host',
    envVar: 'DB_HOST',
    required: true,
    defaultValue: 'localhost',
  },
  {
    name: 'Database Password',
    envVar: 'DB_PASSWORD',
    required: true,
    defaultValue: 'postgres',
  },
  {
    name: 'Blockchain Contract Address',
    envVar: 'RESOURCE_PROVISIONING_CONTRACT_ADDRESS',
    required: false, // Optional if blockchain not used
  },
  {
    name: 'Blockchain Private Key',
    envVar: 'BLOCKCHAIN_PRIVATE_KEY',
    required: false, // Optional if blockchain not used
  },
]

/**
 * Validate that all required secrets are set
 */
export function validateSecrets(): void {
  const isProduction = process.env.NODE_ENV === 'production'
  const missingSecrets: string[] = []
  const usingDefaults: string[] = []

  for (const secret of requiredSecrets) {
    const value = process.env[secret.envVar]
    const defaultValue = secret.defaultValue

    // Skip validation if not production-only or not in production
    if (secret.isProductionOnly && !isProduction) {
      continue
    }

    // Check if required secret is missing
    if (secret.required && !value) {
      missingSecrets.push(secret.name)
      continue
    }

    // Check if using default value in production
    if (isProduction && defaultValue && value === defaultValue) {
      usingDefaults.push(secret.name)
    }
  }

  // Log warnings for defaults in production
  if (usingDefaults.length > 0) {
    logger.warn('Using default values in production (security risk)', {
      secrets: usingDefaults,
    })
  }

  // Fail if required secrets are missing
  if (missingSecrets.length > 0) {
    const error = `Missing required secrets: ${missingSecrets.join(', ')}`
    logger.error(error)
    if (isProduction) {
      throw new Error(error)
    }
  }

  // Log success
  if (isProduction && missingSecrets.length === 0 && usingDefaults.length === 0) {
    logger.info('All production secrets validated successfully')
  }
}

/**
 * Validate database connection string
 */
export function validateDatabaseConfig(): void {
  const required = ['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASSWORD']
  const missing = required.filter((key) => !process.env[key])

  if (missing.length > 0) {
    const error = `Missing database configuration: ${missing.join(', ')}`
    logger.error(error)
    if (process.env.NODE_ENV === 'production') {
      throw new Error(error)
    }
  }
}

