import { z } from "zod";

/**
 * Environment Variables Schema
 *
 * Валидация всех переменных окружения при старте приложения.
 * Ошибки обнаруживаются на этапе сборки, а не в runtime.
 */
const envSchema = z.object({
  // MongoDB
  MONGODB_URI: z
    .string()
    .min(1, "MONGODB_URI is required")
    .default("mongodb://localhost:27017/witlab-funnel"),

  // Build variant
  NEXT_PUBLIC_FUNNEL_BUILD_VARIANT: z
    .enum(["frontend", "full"])
    .optional()
    .default("frontend"),

  // Optional: Base URL for API calls
  NEXT_PUBLIC_BASE_URL: z
    .string()
    .url()
    .optional()
    .default("http://localhost:3000"),

  // Node environment
  NODE_ENV: z
    .enum(["development", "production", "test"])
    .optional()
    .default("development"),

  // Optional: API URL for API calls
  NEXT_PUBLIC_API_URL: z
    .string()
    .url()
    .optional()
    .default("http://localhost:3000"),

  // Optional: Dev logger server enabled
  DEV_LOGGER_SERVER_ENABLED: z.string().optional().default("false"),

  // Optional: Auth redirect URL
  NEXT_PUBLIC_AUTH_REDIRECT_URL: z.string().optional().default("/"),
});

/**
 * Validated environment variables
 * Type-safe access to all env vars
 */
function validateEnv() {
  try {
    return envSchema.parse({
      MONGODB_URI: process.env.MONGODB_URI,
      NEXT_PUBLIC_FUNNEL_BUILD_VARIANT:
        process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT,
      NEXT_PUBLIC_BASE_URL: process.env.NEXT_PUBLIC_BASE_URL,
      NODE_ENV: process.env.NODE_ENV,
      NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
      DEV_LOGGER_SERVER_ENABLED: process.env.DEV_LOGGER_SERVER_ENABLED,
      NEXT_PUBLIC_AUTH_REDIRECT_URL: process.env.NEXT_PUBLIC_AUTH_REDIRECT_URL,
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      console.error("❌ Invalid environment variables:");
      error.issues.forEach((err) => {
        console.error(`  - ${err.path.join(".")}: ${err.message}`);
      });
      throw new Error("Environment validation failed");
    }
    throw error;
  }
}

export const env = validateEnv();

// Type для использования в приложении
export type Env = z.infer<typeof envSchema>;
