// Debug endpoint pour vérifier toutes les variables d'environnement
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  try {
    console.log('🔍 [ENV DEBUG] Analyse des variables d\'environnement');
    
    // Liste des variables importantes à vérifier
    const envVars = [
      'AWS_REGION',
      'AWS_ACCESS_KEY_ID',
      'AWS_SECRET_ACCESS_KEY',
      'AWS_S3_BUCKET',
      'AWS_SES_FROM',
      'DOCUSEAL_TOKEN',
      'DOCUSEAL_API_BASE',
      'PDFMONKEY_URL',
      'PDFMONKEY_API_KEY',
      'GOCARDLESS_ACCESS_TOKEN',
      'GOCARDLESS_ENVIRONMENT',
      'NEXT_PUBLIC_SUPABASE_URL',
      'SUPABASE_SERVICE_ROLE_KEY',
      'S3_BUCKET_NAME',
      'S3_BUCKET_NAME_EMAILS',
      'UPSTREAM_API_BASE'
    ];
    
    const envCheck: Record<string, any> = {};
    
    envVars.forEach(varName => {
      const rawValue = process.env[varName];
      const trimmedValue = rawValue?.trim();
      
      envCheck[varName] = {
        exists: !!rawValue,
        rawLength: rawValue?.length || 0,
        trimmedLength: trimmedValue?.length || 0,
        hasDifference: rawValue !== trimmedValue,
        hasNewlines: rawValue?.includes('\n') || false,
        hasCarriageReturn: rawValue?.includes('\r') || false,
        hasSpaces: rawValue?.startsWith(' ') || rawValue?.endsWith(' ') || false,
        preview: rawValue ? rawValue.substring(0, 20) + '...' : 'undefined'
      };
      
      if (envCheck[varName].hasDifference) {
        console.log(`⚠️ [ENV DEBUG] Variable ${varName} contient des caractères parasites!`, {
          raw: JSON.stringify(rawValue),
          trimmed: JSON.stringify(trimmedValue)
        });
      }
    });
    
    // Compter les variables avec des problèmes
    const problematicVars = Object.entries(envCheck)
      .filter(([_, info]) => info.hasDifference)
      .map(([name]) => name);
    
    return NextResponse.json({
      status: 'Environment Variables Debug',
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV,
      totalVarsChecked: envVars.length,
      problematicVars,
      problematicCount: problematicVars.length,
      details: envCheck
    });
    
  } catch (error) {
    console.error('❌ [ENV DEBUG] Global error:', error);
    return NextResponse.json({
      error: 'Global environment debug error',
      details: error instanceof Error ? error.message : String(error)
    }, { status: 500 });
  }
}