/**
 * Environment variable validation
 * Validates all required environment variables at runtime
 */

import { z } from "zod"

const envSchema = z.object({
  // Stripe Configuration
  NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: z
    .string()
    .min(1, "Stripe publishable key is required")
    .refine((val) => val.startsWith("pk_"), {
      message: "Stripe publishable key must start with 'pk_'",
    }),
  STRIPE_SECRET_KEY: z
    .string()
    .min(1, "Stripe secret key is required")
    .refine((val) => val.startsWith("sk_"), {
      message: "Stripe secret key must start with 'sk_'",
    }),
  STRIPE_WEBHOOK_SECRET: z
    .string()
    .min(1, "Stripe webhook secret is required")
    .refine((val) => val.startsWith("whsec_"), {
      message: "Stripe webhook secret must start with 'whsec_'",
    }),

  // WooCommerce Configuration
  WC_BASE_URL: z.string().url("WooCommerce base URL must be a valid URL"),
  WC_CONSUMER_KEY: z.string().min(1, "WooCommerce consumer key is required"),
  WC_CONSUMER_SECRET: z.string().min(1, "WooCommerce consumer secret is required"),
  NEXT_PUBLIC_WC_BASE_URL: z.string().url("WooCommerce base URL must be a valid URL (public)").optional(),

  // EasyShip Configuration
  EASYSHIP_API_TOKEN: z
    .string()
    .min(20, "EasyShip API token must be at least 20 characters")
    .refine((val) => val.startsWith("prod_") || val.startsWith("sand_"), {
      message: "EasyShip API token must start with 'prod_' or 'sand_'",
    }),
  EASYSHIP_WEBHOOK_SECRET: z.string().optional(),

  // Klaviyo Configuration
  KLAVIYO_API_KEY: z
    .string()
    .min(8, "Klaviyo API key is required")
    .refine((val) => val.startsWith("pk_"), {
      message: "Klaviyo API key must start with 'pk_'",
    }),
  KLAVIYO_ADMIN_EMAIL: z
    .string()
    .email("Klaviyo admin email must be a valid email address"),

  // Security
  CHECKOUT_TOKEN_SECRET: z
    .string()
    .min(32, "Checkout token secret must be at least 32 characters"),

  // Optional Configuration
  CHECKOUT_TOKEN_TTL_SECONDS: z.string().optional().default("900"),
  ALLOWED_ORIGINS: z.string().optional(),
  NODE_ENV: z.enum(["development", "production", "test"]).optional().default("development"),
})

export type Env = z.infer<typeof envSchema>

let cachedEnv: Env | null = null

/**
 * Validate environment variables
 * Exits process if validation fails
 */
export const validateEnv = (): Env => {
  if (cachedEnv) {
    return cachedEnv
  }

  try {
    cachedEnv = envSchema.parse(process.env)
    return cachedEnv
  } catch (error) {
    console.error("❌ Environment validation failed:")
    console.error("")
    if (error instanceof z.ZodError) {
      error.issues.forEach((issue) => {
        console.error(`  • ${issue.path.join(".")}: ${issue.message}`)
      })
    }
    console.error("")
    console.error("Please check your .env.local file and ensure all required variables are set.")
    console.error("See .env.example for the template.")
    process.exit(1)
  }
}

/**
 * Get validated environment variables
 * Call this instead of process.env to ensure type safety
 */
export const env = validateEnv()

