export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

// Debug endpoint pour tester S3 en production
import { NextRequest, NextResponse } from "next/server";
import { s3ObjectExists, getS3SignedUrl } from "@/lib/aws-s3";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const testKey = searchParams.get('key') || 'test-key-that-does-not-exist';
    
    console.log('🔍 [S3 TEST] Testing S3 configuration in production');
    
    // Test des variables d'environnement
    const envCheck = {
      AWS_REGION: process.env.AWS_REGION,
      AWS_S3_BUCKET: process.env.AWS_S3_BUCKET,
      hasAccessKey: !!process.env.AWS_ACCESS_KEY_ID,
      hasSecretKey: !!process.env.AWS_SECRET_ACCESS_KEY,
      accessKeyLength: process.env.AWS_ACCESS_KEY_ID?.length,
      secretKeyLength: process.env.AWS_SECRET_ACCESS_KEY?.length,
      isProduction: process.env.NODE_ENV === 'production'
    };
    
    console.log('🔍 [S3 TEST] Environment variables:', envCheck);
    
    // Test d'existence d'un objet (qui n'existe probablement pas)
    let existsResult;
    try {
      existsResult = await s3ObjectExists(testKey);
      console.log('✅ [S3 TEST] Object exists test completed:', existsResult);
    } catch (error) {
      console.error('❌ [S3 TEST] Error checking object existence:', error);
      existsResult = `ERROR: ${error}`;
    }
    
    // Test de génération d'URL (pour un objet qui n'existe pas - ça devrait quand même générer l'URL)
    let urlResult;
    try {
      urlResult = await getS3SignedUrl(testKey, 60);
      console.log('✅ [S3 TEST] URL generation completed');
    } catch (error) {
      console.error('❌ [S3 TEST] Error generating URL:', error);
      urlResult = `ERROR: ${error}`;
    }
    
    return NextResponse.json({
      status: 'S3 Debug Test',
      environment: envCheck,
      testKey,
      exists: existsResult,
      signedUrl: typeof urlResult === 'string' ? 'Generated successfully' : urlResult,
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('❌ [S3 TEST] Global error:', error);
    return NextResponse.json({
      error: 'Global S3 test error',
      details: error instanceof Error ? error.message : String(error)
    }, { status: 500 });
  }
}