import 'dotenv/config'

const requiredEnvVars = ['FIREBASE_PROJECT_ID'] as const
const recommendedEnvVars = [
  'REVENUECAT_WEBHOOK_SECRET',
  'REVENUECAT_SIGNING_KEY',
  'REVENUECAT_PREMIUM_PRODUCT_IDS',
  'RATE_LIMIT_WEBHOOK',
  'RATE_LIMIT_HEALTH',
  'RATE_LIMIT_DEFAULT',
] as const

type RequiredEnvVar = (typeof requiredEnvVars)[number]
type RecommendedEnvVar = (typeof recommendedEnvVars)[number]

/**
 * Validates that all required environment variables are set.
 * Throws an error with details if any are missing.
 * Logs warnings for missing recommended vars.
 */
export function validateEnv(): void {
  const missing: RequiredEnvVar[] = []
  const missingRecommended: RecommendedEnvVar[] = []

  for (const varName of requiredEnvVars) {
    const value = process.env[varName]
    if (!value || value.trim() === '') {
      missing.push(varName)
    }
  }

  for (const varName of recommendedEnvVars) {
    const value = process.env[varName]
    if (!value || value.trim() === '') {
      missingRecommended.push(varName)
    }
  }

  if (missing.length > 0) {
    const message = missing.map(v => `  - ${v}`).join('\n')
    throw new Error(`Missing required environment variables:\n${message}`)
  }

  // Log warnings for missing recommended vars (not fatal)
  if (missingRecommended.length > 0) {
    console.warn('[env] Missing recommended environment variables (some features disabled):')
    for (const varName of missingRecommended) {
      console.warn(`  - ${varName}`)
    }
  }
}

/**
 * Safely retrieves a required environment variable.
 * Throws if not set (after validateEnv has been called).
 */
export function getEnv(varName: RequiredEnvVar): string {
  const value = process.env[varName]
  if (!value) {
    throw new Error(`Environment variable ${varName} is not set`)
  }
  return value
}

/**
 * Safely retrieves an environment variable (required or recommended).
 * Returns empty string for missing recommended vars (allowing defaults).
 */
export function getEnvValue(varName: string): string {
  const value = process.env[varName]
  return value ?? ''
}

/**
 * Retrieves a rate limit value from env var, with default fallback.
 * Warns if env var is missing and uses default.
 */
export function getRateLimit(varName: string, defaultValue: number): number {
  const value = process.env[varName]
  if (!value) {
    console.warn(`[env] ${varName} not set, using default: ${defaultValue} requests/min`)
    return defaultValue
  }
  const parsed = parseInt(value, 10)
  if (isNaN(parsed) || parsed <= 0) {
    console.warn(`[env] ${varName} has invalid value '${value}', using default: ${defaultValue} requests/min`)
    return defaultValue
  }
  return parsed
}
