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

interface RequiredEnvVars {
  EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: string;
  EXPO_PUBLIC_API_URL: string;
}

interface OptionalEnvVars {
  EXPO_PUBLIC_APP_NAME?: string;
  EXPO_PUBLIC_APP_VERSION?: 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 = [
    "EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY",
    "EXPO_PUBLIC_API_URL",
  ] 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.",
      "",
      "To create your .env file:",
      "1. Copy .env.example to .env",
      "2. Fill in the required values",
    ].join("\n");

    throw new Error(errorMessage);
  }

  // Validate URL format
  const apiUrl = process.env.EXPO_PUBLIC_API_URL!;
  try {
    new URL(apiUrl);
  } catch {
    throw new Error(
      `Invalid EXPO_PUBLIC_API_URL: "${apiUrl}". Must be a valid URL (e.g., http://192.168.1.100:3000)`,
    );
  }

  return {
    EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY:
      process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY!,
    EXPO_PUBLIC_API_URL: process.env.EXPO_PUBLIC_API_URL!,
    EXPO_PUBLIC_APP_NAME: process.env.EXPO_PUBLIC_APP_NAME || "FitAI",
    EXPO_PUBLIC_APP_VERSION: process.env.EXPO_PUBLIC_APP_VERSION || "1.0.0",
    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 __DEV__;
}

/**
 * Check if running in production mode
 */
export function isProduction(): boolean {
  return !__DEV__;
}
