/**
 * Central env validation — run once at server startup.
 * Critical vars throw, optional vars log a warning in dev.
 */

const CRITICAL = [
  "NEXT_PUBLIC_SUPABASE_URL",
  "NEXT_PUBLIC_SUPABASE_ANON_KEY",
  "SUPABASE_SERVICE_ROLE_KEY",
  "DATABASE_URL",
  "NEXT_PUBLIC_APP_URL",
] as const;

const OPTIONAL: Record<string, string> = {
  STRIPE_SECRET_KEY: "Billing/Stripe deaktiviert",
  STRIPE_WEBHOOK_SECRET: "Stripe Webhooks deaktiviert",
  RESEND_API_KEY: "E-Mail-Versand deaktiviert (Einladungen nur gespeichert)",
  INVITE_FROM_EMAIL: "E-Mail-Absender nicht gesetzt",
  OPENAI_API_KEY: "Server-seitiger OpenAI-Key nicht gesetzt (User-Keys funktionieren weiterhin)",
};

export function validateEnv() {
  const missing = CRITICAL.filter((key) => !process.env[key]);

  if (missing.length > 0) {
    throw new Error(
      `[Mindavio] Fehlende kritische Umgebungsvariablen:\n${missing.map((k) => `  • ${k}`).join("\n")}\n\nBitte .env.local prüfen.`,
    );
  }

  if (process.env.NODE_ENV !== "production") {
    for (const [key, hint] of Object.entries(OPTIONAL)) {
      if (!process.env[key]) {
        console.warn(`[Mindavio] Optional nicht gesetzt: ${key} — ${hint}`);
      }
    }
  }
}

/** Type-safe env access — throws if var is missing (use only for server-side code) */
export function requireEnv(key: string): string {
  const value = process.env[key];
  if (!value) throw new Error(`[Mindavio] Env var "${key}" ist nicht gesetzt.`);
  return value;
}

/** Safe env access — returns null if missing instead of throwing */
export function optionalEnv(key: string): string | null {
  return process.env[key] ?? null;
}
