import * as Joi from 'joi';

export type NodeEnvironment = 'development' | 'test' | 'production';
export type EvidenceStorageProvider = 'synthetic' | 'supabase';
export type PaymentProviderMode = 'synthetic' | 'disabled';
export type FirebaseAuthMode = 'disabled' | 'firebase';
export type AiProviderMode = 'disabled' | 'gemini';
export type AiFallbackProviderMode = 'disabled' | 'groq';
export type AiUseCaseMode = 'disabled' | 'synthetic';
export type EmailProviderMode = 'disabled' | 'resend';
export type WhatsAppProviderMode = 'disabled' | 'meta_cloud';
export type GoogleMapsBackendMode = 'disabled' | 'google_maps';
export type DirektTrafficMode = 'disabled' | 'internal' | 'synthetic-public' | 'controlled-pilot';
export type DirektDataMode = 'synthetic-only' | 'controlled-pilot' | 'production';
export type DirektDeploymentEnvironment =
  'local' | 'development' | 'staging' | 'pilot' | 'production';

export interface DirektEnvironment {
  NODE_ENV: NodeEnvironment;
  PORT: number;
  LOG_LEVEL: 'debug' | 'info' | 'warn' | 'error';
  DATABASE_URL: string;
  DIRECT_DATABASE_URL?: string;
  CORS_ORIGINS: string;
  TRUST_PROXY_HOPS: number;
  DIREKT_ENVIRONMENT: DirektDeploymentEnvironment;
  DIREKT_DATA_MODE: DirektDataMode;
  DIREKT_TRAFFIC_MODE: DirektTrafficMode;
  PILOT_ENTRY_APPROVED: boolean;
  PILOT_NOTICE_VERSION?: string;
  RATE_LIMITS_ENABLED: boolean;
  RATE_LIMIT_HASH_PEPPER: string;
  AUTH_CHALLENGE_MODE: 'synthetic' | 'disabled';
  FIREBASE_AUTH_MODE: FirebaseAuthMode;
  FIREBASE_PROJECT_ID?: string;
  FIREBASE_MAX_AUTH_AGE_SECONDS: number;
  ACCESS_TOKEN_SECRET: string;
  CONTACT_HASH_PEPPER: string;
  CHALLENGE_HASH_PEPPER: string;
  EXTERNAL_SUBJECT_HASH_PEPPER?: string;
  ACCESS_TOKEN_TTL_SECONDS: number;
  REFRESH_TOKEN_TTL_DAYS: number;
  CHALLENGE_TTL_SECONDS: number;
  EVIDENCE_STORAGE_PROVIDER: EvidenceStorageProvider;
  SUPABASE_URL?: string;
  SUPABASE_SECRET_KEY?: string;
  SUPABASE_SERVICE_ROLE_KEY?: string;
  SUPABASE_EVIDENCE_BUCKET: string;
  SUPABASE_PRIVATE_MEDIA_BUCKET: string;
  SUPABASE_PUBLIC_MEDIA_BUCKET: string;
  SUPABASE_SYSTEM_EXPORTS_BUCKET: string;
  PAYMENT_PROVIDER_MODE: PaymentProviderMode;
  PAYMENT_SYNTHETIC_WEBHOOK_SECRET?: string;
  AI_PROVIDER_MODE: AiProviderMode;
  AI_FALLBACK_PROVIDER: AiFallbackProviderMode;
  AI_GEMINI_API_KEY?: string;
  AI_GEMINI_MODEL: string;
  AI_GROQ_API_KEY?: string;
  AI_GROQ_MODEL: string;
  AI_REQUEST_TIMEOUT_MS: number;
  AI_MAX_INPUT_CHARS: number;
  DIREKT_AI_DISCOVERY_ASSIST_MODE: AiUseCaseMode;
  DIREKT_AI_PUBLIC_SUPPORT_MODE: AiUseCaseMode;
  DIREKT_AI_PROVIDER_GUIDE_MODE: AiUseCaseMode;
  DIREKT_AI_PROVIDER_DRAFT_MODE: AiUseCaseMode;
  DIREKT_AI_OPERATIONS_SUMMARY_MODE: 'disabled';
  EMAIL_PROVIDER_MODE: EmailProviderMode;
  EMAIL_RESEND_API_KEY?: string;
  EMAIL_FROM_ADDRESS: string;
  EMAIL_REQUEST_TIMEOUT_MS: number;
  EMAIL_MAX_ATTEMPTS: number;
  EMAIL_OUTBOX_LOCK_TIMEOUT_MS: number;
  WHATSAPP_PROVIDER_MODE: WhatsAppProviderMode;
  WHATSAPP_ACCESS_TOKEN?: string;
  WHATSAPP_PHONE_NUMBER_ID?: string;
  WHATSAPP_BUSINESS_ACCOUNT_ID?: string;
  WHATSAPP_APP_SECRET?: string;
  WHATSAPP_WEBHOOK_VERIFY_TOKEN?: string;
  WHATSAPP_GRAPH_API_VERSION?: string;
  WHATSAPP_REQUEST_TIMEOUT_MS: number;
  WHATSAPP_MAX_ATTEMPTS: number;
  WHATSAPP_OUTBOX_LOCK_TIMEOUT_MS: number;
  WHATSAPP_SYNTHETIC_SEND_APPROVED: boolean;
  WHATSAPP_SYNTHETIC_RECIPIENT?: string;
  WHATSAPP_SYNTHETIC_TEMPLATE_NAME?: string;
  WHATSAPP_SYNTHETIC_TEMPLATE_LANGUAGE: string;
  GOOGLE_MAPS_BACKEND_MODE: GoogleMapsBackendMode;
  GOOGLE_MAPS_OAUTH_SCOPE: string;
  GOOGLE_MAPS_GEOCODING_ENDPOINT: string;
  GOOGLE_MAPS_REQUEST_TIMEOUT_MS: number;
  GOOGLE_MAPS_SYNTHETIC_CANARY_APPROVED: boolean;
}

const databaseUrlSchema = Joi.string().uri({ scheme: ['postgresql', 'postgres'] });
const longSecret = Joi.string().min(64).max(512);
const providerApiKey = Joi.string().trim().min(20).max(4096);
const providerModelName = Joi.string().trim().min(3).max(160);
const supabaseServerKey = Joi.string().min(20).max(2048);
const bucketName = Joi.string().pattern(/^[a-z0-9][a-z0-9-]{1,62}$/);
const firebaseProjectId = Joi.string().pattern(/^[a-z][a-z0-9-]{4,29}$/);
const resendFromAddress = Joi.string().trim().min(10).max(320);
const whatsappNumericId = Joi.string().pattern(/^\d{5,32}$/);
const whatsappGraphVersion = Joi.string().pattern(/^v\d{1,3}\.\d{1,2}$/);
const whatsappVerifyToken = Joi.string().trim().min(20).max(256);
const whatsappAppSecret = Joi.string().trim().min(32).max(512);
const whatsappRecipient = Joi.string().pattern(/^\+[1-9]\d{7,14}$/);
const whatsappTemplateName = Joi.string().pattern(/^[a-z][a-z0-9_]{2,79}$/);
const whatsappTemplateLanguage = Joi.string().pattern(/^[a-z]{2,3}(_[A-Z]{2})?$/);
const googleMapsOAuthScope = Joi.string().valid(
  'https://www.googleapis.com/auth/maps-platform.geocode.address',
);
const googleMapsEndpoint = Joi.string().valid('https://geocode.googleapis.com/v4/geocode/address');

export const environmentSchema = Joi.object<DirektEnvironment>({
  NODE_ENV: Joi.string().valid('development', 'test', 'production').default('development'),
  PORT: Joi.number().integer().min(1).max(65535).default(3000),
  LOG_LEVEL: Joi.string().valid('debug', 'info', 'warn', 'error').default('info'),
  DATABASE_URL: databaseUrlSchema.when('NODE_ENV', {
    is: 'production',
    then: databaseUrlSchema.required(),
    otherwise: databaseUrlSchema.default('postgresql://direkt:direkt_dev@localhost:5432/direkt'),
  }),
  DIRECT_DATABASE_URL: databaseUrlSchema.optional(),
  CORS_ORIGINS: Joi.string().allow('').default(''),
  TRUST_PROXY_HOPS: Joi.number().integer().min(0).max(2).default(0),
  DIREKT_ENVIRONMENT: Joi.string()
    .valid('local', 'development', 'staging', 'pilot', 'production')
    .default('local'),
  DIREKT_DATA_MODE: Joi.string()
    .valid('synthetic-only', 'controlled-pilot', 'production')
    .default('synthetic-only'),
  DIREKT_TRAFFIC_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled', 'controlled-pilot').default('disabled'),
    otherwise: Joi.valid('disabled', 'internal', 'synthetic-public', 'controlled-pilot').default(
      'internal',
    ),
  }),
  PILOT_ENTRY_APPROVED: Joi.boolean().truthy('true').falsy('false').default(false),
  PILOT_NOTICE_VERSION: Joi.string().trim().min(3).max(120).when('FIREBASE_AUTH_MODE', {
    is: 'firebase',
    then: Joi.required(),
    otherwise: Joi.optional(),
  }),
  RATE_LIMITS_ENABLED: Joi.boolean()
    .truthy('true')
    .falsy('false')
    .when('NODE_ENV', {
      is: 'test',
      then: Joi.boolean().default(false),
      otherwise: Joi.boolean().default(true),
    }),
  RATE_LIMIT_HASH_PEPPER: longSecret.when('NODE_ENV', {
    is: 'production',
    then: longSecret.required(),
    otherwise: longSecret.default(
      'direkt-development-rate-limit-hash-pepper-not-for-production-000001',
    ),
  }),
  AUTH_CHALLENGE_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('synthetic', 'disabled').default('synthetic'),
  }),
  FIREBASE_AUTH_MODE: Joi.string().valid('disabled', 'firebase').default('disabled'),
  FIREBASE_PROJECT_ID: firebaseProjectId.when('FIREBASE_AUTH_MODE', {
    is: 'firebase',
    then: firebaseProjectId.required(),
    otherwise: firebaseProjectId.optional(),
  }),
  FIREBASE_MAX_AUTH_AGE_SECONDS: Joi.number().integer().min(60).max(900).default(300),
  ACCESS_TOKEN_SECRET: longSecret.when('NODE_ENV', {
    is: 'production',
    then: longSecret.required(),
    otherwise: longSecret.default(
      'direkt-development-access-token-secret-not-for-production-000000000001',
    ),
  }),
  CONTACT_HASH_PEPPER: longSecret.when('NODE_ENV', {
    is: 'production',
    then: longSecret.required(),
    otherwise: longSecret.default(
      'direkt-development-contact-hash-pepper-not-for-production-000000001',
    ),
  }),
  CHALLENGE_HASH_PEPPER: longSecret.when('NODE_ENV', {
    is: 'production',
    then: longSecret.required(),
    otherwise: longSecret.default(
      'direkt-development-challenge-hash-pepper-not-for-production-0000001',
    ),
  }),
  EXTERNAL_SUBJECT_HASH_PEPPER: longSecret.when('FIREBASE_AUTH_MODE', {
    is: 'firebase',
    then: longSecret.required(),
    otherwise: Joi.optional(),
  }),
  ACCESS_TOKEN_TTL_SECONDS: Joi.number().integer().min(60).max(900).default(600),
  REFRESH_TOKEN_TTL_DAYS: Joi.number().integer().min(1).max(90).default(30),
  CHALLENGE_TTL_SECONDS: Joi.number().integer().min(60).max(600).default(300),
  EVIDENCE_STORAGE_PROVIDER: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('supabase').default('supabase'),
    otherwise: Joi.valid('synthetic', 'supabase').default('synthetic'),
  }),
  SUPABASE_URL: Joi.string()
    .uri({ scheme: ['https'] })
    .when('EVIDENCE_STORAGE_PROVIDER', {
      is: 'supabase',
      then: Joi.required(),
      otherwise: Joi.optional(),
    }),
  SUPABASE_SECRET_KEY: supabaseServerKey.optional(),
  SUPABASE_SERVICE_ROLE_KEY: supabaseServerKey.optional(),
  SUPABASE_EVIDENCE_BUCKET: bucketName.default('provider-evidence'),
  SUPABASE_PRIVATE_MEDIA_BUCKET: bucketName.default('provider-media-private'),
  SUPABASE_PUBLIC_MEDIA_BUCKET: bucketName.default('provider-media-public'),
  SUPABASE_SYSTEM_EXPORTS_BUCKET: bucketName.default('system-exports'),
  PAYMENT_PROVIDER_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('synthetic', 'disabled').default('synthetic'),
  }),
  PAYMENT_SYNTHETIC_WEBHOOK_SECRET: longSecret.when('PAYMENT_PROVIDER_MODE', {
    is: 'synthetic',
    then: longSecret.default(
      'direkt-development-synthetic-payment-webhook-secret-not-for-production-0001',
    ),
    otherwise: Joi.optional(),
  }),
  AI_PROVIDER_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('disabled', 'gemini').default('disabled'),
  }),
  AI_FALLBACK_PROVIDER: Joi.string().valid('disabled', 'groq').default('disabled'),
  AI_GEMINI_API_KEY: providerApiKey.when('AI_PROVIDER_MODE', {
    is: 'gemini',
    then: providerApiKey.required(),
    otherwise: providerApiKey.optional(),
  }),
  AI_GEMINI_MODEL: providerModelName.default('gemini-3.5-flash'),
  AI_GROQ_API_KEY: providerApiKey.when('AI_FALLBACK_PROVIDER', {
    is: 'groq',
    then: providerApiKey.required(),
    otherwise: providerApiKey.optional(),
  }),
  AI_GROQ_MODEL: providerModelName.default('openai/gpt-oss-20b'),
  AI_REQUEST_TIMEOUT_MS: Joi.number().integer().min(1000).max(30000).default(8000),
  AI_MAX_INPUT_CHARS: Joi.number().integer().min(256).max(20000).default(8000),
  DIREKT_AI_DISCOVERY_ASSIST_MODE: Joi.string().valid('disabled', 'synthetic').default('disabled'),
  DIREKT_AI_PUBLIC_SUPPORT_MODE: Joi.string().valid('disabled', 'synthetic').default('disabled'),
  DIREKT_AI_PROVIDER_GUIDE_MODE: Joi.string().valid('disabled', 'synthetic').default('disabled'),
  DIREKT_AI_PROVIDER_DRAFT_MODE: Joi.string().valid('disabled', 'synthetic').default('disabled'),
  DIREKT_AI_OPERATIONS_SUMMARY_MODE: Joi.string().valid('disabled').default('disabled'),
  EMAIL_PROVIDER_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('disabled', 'resend').default('disabled'),
  }),
  EMAIL_RESEND_API_KEY: providerApiKey.when('EMAIL_PROVIDER_MODE', {
    is: 'resend',
    then: providerApiKey.required(),
    otherwise: providerApiKey.optional(),
  }),
  EMAIL_FROM_ADDRESS: resendFromAddress.default('DIREKT <canary@notify.direkt.forum>'),
  EMAIL_REQUEST_TIMEOUT_MS: Joi.number().integer().min(1000).max(30000).default(8000),
  EMAIL_MAX_ATTEMPTS: Joi.number().integer().min(1).max(6).default(4),
  EMAIL_OUTBOX_LOCK_TIMEOUT_MS: Joi.number().integer().min(30000).max(900000).default(300000),
  WHATSAPP_PROVIDER_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('disabled', 'meta_cloud').default('disabled'),
  }),
  WHATSAPP_ACCESS_TOKEN: providerApiKey.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: providerApiKey.required(),
    otherwise: providerApiKey.optional(),
  }),
  WHATSAPP_PHONE_NUMBER_ID: whatsappNumericId.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappNumericId.required(),
    otherwise: whatsappNumericId.optional(),
  }),
  WHATSAPP_BUSINESS_ACCOUNT_ID: whatsappNumericId.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappNumericId.required(),
    otherwise: whatsappNumericId.optional(),
  }),
  WHATSAPP_APP_SECRET: whatsappAppSecret.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappAppSecret.required(),
    otherwise: whatsappAppSecret.optional(),
  }),
  WHATSAPP_WEBHOOK_VERIFY_TOKEN: whatsappVerifyToken.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappVerifyToken.required(),
    otherwise: whatsappVerifyToken.optional(),
  }),
  WHATSAPP_GRAPH_API_VERSION: whatsappGraphVersion.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappGraphVersion.required(),
    otherwise: whatsappGraphVersion.optional(),
  }),
  WHATSAPP_REQUEST_TIMEOUT_MS: Joi.number().integer().min(1000).max(30000).default(8000),
  WHATSAPP_MAX_ATTEMPTS: Joi.number().integer().min(1).max(6).default(4),
  WHATSAPP_OUTBOX_LOCK_TIMEOUT_MS: Joi.number().integer().min(30000).max(900000).default(300000),
  WHATSAPP_SYNTHETIC_SEND_APPROVED: Joi.boolean().truthy('true').falsy('false').default(false),
  WHATSAPP_SYNTHETIC_RECIPIENT: whatsappRecipient.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappRecipient.required(),
    otherwise: whatsappRecipient.optional(),
  }),
  WHATSAPP_SYNTHETIC_TEMPLATE_NAME: whatsappTemplateName.when('WHATSAPP_PROVIDER_MODE', {
    is: 'meta_cloud',
    then: whatsappTemplateName.required(),
    otherwise: whatsappTemplateName.optional(),
  }),
  WHATSAPP_SYNTHETIC_TEMPLATE_LANGUAGE: whatsappTemplateLanguage.default('en_US'),
  GOOGLE_MAPS_BACKEND_MODE: Joi.string().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid('disabled').default('disabled'),
    otherwise: Joi.valid('disabled', 'google_maps').default('disabled'),
  }),
  GOOGLE_MAPS_OAUTH_SCOPE: googleMapsOAuthScope.default(
    'https://www.googleapis.com/auth/maps-platform.geocode.address',
  ),
  GOOGLE_MAPS_GEOCODING_ENDPOINT: googleMapsEndpoint.default(
    'https://geocode.googleapis.com/v4/geocode/address',
  ),
  GOOGLE_MAPS_REQUEST_TIMEOUT_MS: Joi.number().integer().min(1000).max(15000).default(5000),
  GOOGLE_MAPS_SYNTHETIC_CANARY_APPROVED: Joi.boolean().truthy('true').falsy('false').default(false),
}).custom((value: DirektEnvironment, helpers) => {
  if (
    value.EVIDENCE_STORAGE_PROVIDER === 'supabase' &&
    !value.SUPABASE_SECRET_KEY &&
    !value.SUPABASE_SERVICE_ROLE_KEY
  ) {
    return helpers.message({
      custom: 'SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY is required for Supabase storage.',
    });
  }
  if (value.NODE_ENV === 'production' && value.PAYMENT_PROVIDER_MODE !== 'disabled') {
    return helpers.message({
      custom: 'Production payment provider mode must remain disabled until a later approval gate.',
    });
  }
  if (value.NODE_ENV === 'production' && value.AI_PROVIDER_MODE !== 'disabled') {
    return helpers.message({
      custom:
        'Production AI provider mode must remain disabled until a later privacy and release gate.',
    });
  }
  if (value.NODE_ENV === 'production' && value.EMAIL_PROVIDER_MODE !== 'disabled') {
    return helpers.message({
      custom: 'Production email provider mode must remain disabled until a later approval gate.',
    });
  }
  if (value.NODE_ENV === 'production' && value.WHATSAPP_PROVIDER_MODE !== 'disabled') {
    return helpers.message({
      custom:
        'Production WhatsApp provider mode must remain disabled until later provider/legal/privacy and release gates.',
    });
  }
  if (value.NODE_ENV === 'production' && value.GOOGLE_MAPS_BACKEND_MODE !== 'disabled') {
    return helpers.message({
      custom:
        'Production Google Maps backend mode must remain disabled until later participant and release gates.',
    });
  }
  if (value.AI_PROVIDER_MODE !== 'disabled' && value.DIREKT_DATA_MODE !== 'synthetic-only') {
    return helpers.message({
      custom: 'AI provider activation currently permits synthetic-only data mode.',
    });
  }
  if (value.AI_FALLBACK_PROVIDER !== 'disabled' && value.AI_PROVIDER_MODE === 'disabled') {
    return helpers.message({
      custom: 'AI fallback provider cannot be enabled while the primary AI provider is disabled.',
    });
  }
  const enabledAiUseCases = [
    value.DIREKT_AI_DISCOVERY_ASSIST_MODE,
    value.DIREKT_AI_PUBLIC_SUPPORT_MODE,
    value.DIREKT_AI_PROVIDER_GUIDE_MODE,
    value.DIREKT_AI_PROVIDER_DRAFT_MODE,
  ].some((mode) => mode === 'synthetic');
  if (enabledAiUseCases && value.DIREKT_DATA_MODE !== 'synthetic-only') {
    return helpers.message({
      custom: 'AI use-case activation currently permits synthetic-only data mode.',
    });
  }
  if (enabledAiUseCases && value.AI_PROVIDER_MODE === 'disabled') {
    return helpers.message({
      custom: 'AI use-case activation requires an explicitly enabled primary AI provider.',
    });
  }
  if (value.EMAIL_PROVIDER_MODE !== 'disabled' && value.DIREKT_DATA_MODE !== 'synthetic-only') {
    return helpers.message({
      custom: 'Email provider activation currently permits synthetic-only data mode.',
    });
  }
  if (
    value.EMAIL_PROVIDER_MODE === 'resend' &&
    !/^[^<>]*<[^@\s<>]+@notify\.direkt\.forum>$/.test(value.EMAIL_FROM_ADDRESS)
  ) {
    return helpers.message({
      custom: 'Resend sender must use the verified notify.direkt.forum domain.',
    });
  }
  if (value.WHATSAPP_PROVIDER_MODE !== 'disabled') {
    if (value.DIREKT_DATA_MODE !== 'synthetic-only') {
      return helpers.message({
        custom: 'WhatsApp provider activation currently permits synthetic-only data mode.',
      });
    }
    if (!value.WHATSAPP_SYNTHETIC_SEND_APPROVED) {
      return helpers.message({
        custom: 'WhatsApp provider activation requires the explicit synthetic-send approval latch.',
      });
    }
  }
  if (value.GOOGLE_MAPS_BACKEND_MODE !== 'disabled') {
    if (value.DIREKT_DATA_MODE !== 'synthetic-only') {
      return helpers.message({
        custom: 'Google Maps backend activation currently permits synthetic-only data mode.',
      });
    }
    if (!value.GOOGLE_MAPS_SYNTHETIC_CANARY_APPROVED) {
      return helpers.message({
        custom:
          'Google Maps backend activation requires the explicit synthetic Maps approval latch.',
      });
    }
  }
  if (
    value.DIREKT_TRAFFIC_MODE === 'synthetic-public' &&
    value.DIREKT_DATA_MODE !== 'synthetic-only'
  ) {
    return helpers.message({
      custom: 'Public synthetic traffic requires DIREKT_DATA_MODE=synthetic-only.',
    });
  }
  if (value.FIREBASE_AUTH_MODE === 'firebase') {
    if (
      value.DIREKT_ENVIRONMENT !== 'pilot' ||
      value.DIREKT_DATA_MODE !== 'controlled-pilot' ||
      !value.PILOT_ENTRY_APPROVED
    ) {
      return helpers.message({
        custom:
          'Firebase authentication may be enabled only for the explicitly approved controlled-pilot environment.',
      });
    }
  }
  if (value.DIREKT_TRAFFIC_MODE === 'controlled-pilot') {
    if (
      value.DIREKT_ENVIRONMENT !== 'pilot' ||
      value.DIREKT_DATA_MODE !== 'controlled-pilot' ||
      !value.PILOT_ENTRY_APPROVED ||
      value.FIREBASE_AUTH_MODE !== 'firebase'
    ) {
      return helpers.message({
        custom:
          'Controlled-pilot traffic requires the pilot environment, controlled-pilot data mode, explicit entry approval and Firebase authentication.',
      });
    }
  }
  if (value.PILOT_ENTRY_APPROVED && value.DIREKT_DATA_MODE !== 'controlled-pilot') {
    return helpers.message({
      custom: 'PILOT_ENTRY_APPROVED may be true only with DIREKT_DATA_MODE=controlled-pilot.',
    });
  }
  if (value.DIREKT_DATA_MODE === 'controlled-pilot') {
    if (!value.PILOT_ENTRY_APPROVED) {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires the explicit PILOT_ENTRY_APPROVED technical latch.',
      });
    }
    if (value.DIREKT_ENVIRONMENT !== 'pilot') {
      return helpers.message({
        custom: 'Controlled-pilot data mode requires DIREKT_ENVIRONMENT=pilot.',
      });
    }
    if (value.EVIDENCE_STORAGE_PROVIDER !== 'supabase') {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires the approved private Supabase storage boundary.',
      });
    }
    if (value.AUTH_CHALLENGE_MODE !== 'disabled') {
      return helpers.message({
        custom: 'Controlled-pilot data mode cannot use synthetic authentication challenges.',
      });
    }
    if (value.PAYMENT_PROVIDER_MODE !== 'disabled') {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires payments to remain disabled until separately approved.',
      });
    }
    if (value.AI_PROVIDER_MODE !== 'disabled') {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires AI providers to remain disabled until separately approved.',
      });
    }
    if (value.EMAIL_PROVIDER_MODE !== 'disabled') {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires external email delivery to remain disabled until separately approved.',
      });
    }
    if (value.WHATSAPP_PROVIDER_MODE !== 'disabled') {
      return helpers.message({
        custom:
          'Controlled-pilot data mode requires WhatsApp delivery to remain disabled until separately approved.',
      });
    }
    if (!['disabled', 'controlled-pilot'].includes(value.DIREKT_TRAFFIC_MODE)) {
      return helpers.message({
        custom:
          'Controlled-pilot data mode remains traffic-disabled until an approved participant access and authentication path is implemented.',
      });
    }
  }
  if (value.DIREKT_TRAFFIC_MODE === 'controlled-pilot' && !value.FIREBASE_PROJECT_ID) {
    return helpers.message({
      custom: 'Controlled-pilot traffic requires an approved Firebase project binding.',
    });
  }
  if (value.DIREKT_DATA_MODE === 'production' && value.DIREKT_TRAFFIC_MODE !== 'disabled') {
    return helpers.message({
      custom: 'Production traffic must remain disabled until the Phase 12 release gate.',
    });
  }
  return value;
});

export function parseCorsOrigins(value: string | undefined): string[] {
  if (!value?.trim()) {
    return [];
  }

  return value
    .split(',')
    .map((origin) => origin.trim())
    .filter(Boolean);
}
