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

// app/api/debug/pdf-diagnosis/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";
import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";

export async function GET(request: NextRequest) {
  try {
    const sb = createSbServer();
    
    // Vérification de l'authentification et du staff
    const { data: { user }, error: authError } = await sb.auth.getUser();
    if (authError || !user) {
      return NextResponse.json(
        { error: "Authentification requise" },
        { status: 401 }
      );
    }

    const { data: staffUser } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();

    if (!staffUser?.is_staff) {
      return NextResponse.json(
        { error: "Accès refusé - réservé au staff" },
        { status: 403 }
      );
    }

    // Get a sample of contracts with their PDF filenames
    const { data: contracts, error: contractsError } = await sb
      .from("cddu_contracts")
      .select(`
        id,
        contract_number,
        contract_pdf_filename,
        employee_name
      `)
      .order("created_at", { ascending: false })
      .limit(10);

    if (contractsError) {
      return NextResponse.json(
        { error: "Erreur lors de la récupération des contrats", details: contractsError },
        { status: 500 }
      );
    }

    // Configuration S3
    const s3Client = new S3Client({
      region: process.env.AWS_REGION || "eu-west-3",
      credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
      },
    });

    // List some files in the unsigned-contracts folder
    const listCommand = new ListObjectsV2Command({
      Bucket: (process.env.AWS_S3_BUCKET || "odentas-docs").trim(),
      Prefix: "unsigned-contracts/",
      MaxKeys: 20
    });

    const s3Objects = await s3Client.send(listCommand);

    const analysis = {
      database_contracts: contracts?.map(c => ({
        id: c.id,
        contract_number: c.contract_number,
        employee_name: c.employee_name,
        contract_pdf_filename: c.contract_pdf_filename,
        has_filename: !!c.contract_pdf_filename,
        filename_length: c.contract_pdf_filename?.length || 0
      })) || [],
      s3_files: s3Objects.Contents?.map(obj => ({
        key: obj.Key,
        size: obj.Size,
        lastModified: obj.LastModified
      })) || [],
      statistics: {
        total_contracts_checked: contracts?.length || 0,
        contracts_with_filename: contracts?.filter(c => c.contract_pdf_filename).length || 0,
        contracts_without_filename: contracts?.filter(c => !c.contract_pdf_filename).length || 0,
        s3_files_count: s3Objects.Contents?.length || 0
      }
    };

    return NextResponse.json({
      success: true,
      data: analysis
    });

  } catch (error) {
    console.error("Erreur lors du diagnostic PDF:", error);
    return NextResponse.json(
      { 
        error: "Erreur interne du serveur", 
        details: error instanceof Error ? error.message : String(error) 
      },
      { status: 500 }
    );
  }
}