// lib/cleanEnv.ts - Utilitaire pour nettoyer les variables d'environnement
export function cleanEnv(key: string, fallback?: string): string {
  const value = process.env[key];
  if (!value) {
    return fallback || '';
  }
  
  // Nettoyer tous les caractères parasites
  const cleaned = value
    .trim()                    // Supprimer espaces en début/fin
    .replace(/\n/g, '')        // Supprimer retours à la ligne
    .replace(/\r/g, '')        // Supprimer retours chariot
    .replace(/\t/g, '');       // Supprimer tabulations
    
  return cleaned;
}

// Variables d'environnement pré-nettoyées
export const ENV = {
  // AWS
  AWS_REGION: cleanEnv('AWS_REGION', 'eu-west-3'),
  AWS_ACCESS_KEY_ID: cleanEnv('AWS_ACCESS_KEY_ID'),
  AWS_SECRET_ACCESS_KEY: cleanEnv('AWS_SECRET_ACCESS_KEY'),
  AWS_S3_BUCKET: cleanEnv('AWS_S3_BUCKET', 'odentas-docs'),
  AWS_SES_FROM: cleanEnv('AWS_SES_FROM', 'paie@odentas.fr'),
  
  // DocuSeal
  DOCUSEAL_TOKEN: cleanEnv('DOCUSEAL_TOKEN'),
  DOCUSEAL_API_BASE: cleanEnv('DOCUSEAL_API_BASE', 'https://api.docuseal.eu'),
  
  // PDFMonkey
  PDFMONKEY_URL: cleanEnv('PDFMONKEY_URL'),
  PDFMONKEY_API_KEY: cleanEnv('PDFMONKEY_API_KEY'),
  
  // GoCardless
  GOCARDLESS_ACCESS_TOKEN: cleanEnv('GOCARDLESS_ACCESS_TOKEN'),
  GOCARDLESS_ENVIRONMENT: cleanEnv('GOCARDLESS_ENVIRONMENT'),
  
  // Supabase
  NEXT_PUBLIC_SUPABASE_URL: cleanEnv('NEXT_PUBLIC_SUPABASE_URL'),
  SUPABASE_SERVICE_ROLE_KEY: cleanEnv('SUPABASE_SERVICE_ROLE_KEY'),
  
  // S3 Buckets
  S3_BUCKET_NAME: cleanEnv('S3_BUCKET_NAME', 'odentas-docs'),
  S3_BUCKET_NAME_EMAILS: cleanEnv('S3_BUCKET_NAME_EMAILS'),
  
  // APIs
  UPSTREAM_API_BASE: cleanEnv('UPSTREAM_API_BASE'),
  
  // Sécurité
  LAMBDA_API_KEY: cleanEnv('LAMBDA_API_KEY'),
  
  // Autres
  NODE_ENV: process.env.NODE_ENV
};