import { z } from 'zod';
import { validateMintelEnv, mintelEnvSchema, withMintelRefinements } from '@mintel/next-utils';

/**
 * Robust boolean preprocessor for environment variables.
 * Handles strings 'true'/'false' and actual booleans.
 */
const booleanSchema = z.preprocess((val) => {
  if (typeof val === 'string') {
    if (val.toLowerCase() === 'true') return true;
    if (val.toLowerCase() === 'false') return false;
  }
  return val;
}, z.boolean());

/**
 * Environment variable schema.
 * Extends the default Mintel environment schema.
 */
const envExtension = {
  // Project specific overrides or additions
  AUTH_COOKIE_NAME: z.string().default('klz_gatekeeper_session'),
  TARGET: z.string().optional(),
  NEXT_PUBLIC_TARGET: z.string().optional(),

  // Gatekeeper specifics not in base
  GATEKEEPER_URL: z.string().url().default('http://gatekeeper:3000'),
  GATEKEEPER_BYPASS_ENABLED: booleanSchema.default(false),
  NEXT_PUBLIC_FEEDBACK_ENABLED: booleanSchema.default(false),
  NEXT_PUBLIC_RECORD_MODE_ENABLED: booleanSchema.default(false),

  INFRA_DIRECTUS_URL: z.string().url().optional(),
  INFRA_DIRECTUS_TOKEN: z.string().optional(),

  // Analytics
  UMAMI_WEBSITE_ID: z.string().optional(),
  UMAMI_API_ENDPOINT: z.string().optional(),

  // Mail Configuration
  MAIL_HOST: z.string().optional(),
  MAIL_PORT: z.coerce.number().optional(),
  MAIL_USERNAME: z.string().optional(),
  MAIL_PASSWORD: z.string().optional(),
  MAIL_FROM: z.string().optional(),
  MAIL_RECIPIENTS: z.string().trim().optional(),
};

/**
 * Full schema including Mintel base and refinements
 */
export const envSchema = withMintelRefinements(z.object(mintelEnvSchema).extend(envExtension));

/**
 * Validated environment object.
 */
export const env = validateMintelEnv(envExtension);

/**
 * For legacy compatibility with existing code.
 */
export function getRawEnv() {
  return env;
}
