/**
 * Environment variable validation for admin app
 * Validates that all required environment variables are set
 */

interface RequiredEnvVars {
  NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: string;
  CLERK_SECRET_KEY: string;
  DEEPSEEK_API_KEY: string;
}

interface OptionalEnvVars {
  CLERK_WEBHOOK_SECRET?: string;
  DATABASE_PATH?: string;
  NODE_ENV?: string;
}

type EnvVars = RequiredEnvVars & OptionalEnvVars;

/**
 * Validate required environment variables
 * Throws error if any required variable is missing
 */
export function validateEnv(): EnvVars {
  const errors: string[] = [];

  // Required variables
  const requiredVars = [
    "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY",
    "CLERK_SECRET_KEY",
    "DEEPSEEK_API_KEY",
  ] as const;

  for (const varName of requiredVars) {
    if (!process.env[varName]) {
      errors.push(`Missing required environment variable: ${varName}`);
    }
  }

  if (errors.length > 0) {
    const errorMessage = [
      "❌ Environment validation failed:",
      ...errors,
      "",
      "Please check your .env file and ensure all required variables are set.",
      "See .env.example for the list of required variables.",
    ].join("\n");

    throw new Error(errorMessage);
  }

  return {
    NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:
      process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY!,
    CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY!,
    DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY!,
    CLERK_WEBHOOK_SECRET: process.env.CLERK_WEBHOOK_SECRET,
    DATABASE_PATH: process.env.DATABASE_PATH || "./fitai.db",
    NODE_ENV: process.env.NODE_ENV || "development",
  };
}

/**
 * Get validated environment variables
 * Caches the result after first validation
 */
let cachedEnv: EnvVars | null = null;

export function getEnv(): EnvVars {
  if (!cachedEnv) {
    cachedEnv = validateEnv();
  }
  return cachedEnv;
}

/**
 * Check if running in development mode
 */
export function isDevelopment(): boolean {
  return getEnv().NODE_ENV === "development";
}

/**
 * Check if running in production mode
 */
export function isProduction(): boolean {
  return getEnv().NODE_ENV === "production";
}
