// app/api/contrats/[id]/pdf-url/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  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 }
      );
    }

    // Récupération du contrat et de l'URL du PDF
    const { data: contract, error: contractError } = await sb
      .from("cddu_contracts")
      .select("contract_pdf_filename, contract_number, employee_name")
      .eq("id", params.id)
      .single();

    if (contractError) {
      return NextResponse.json(
        { error: "Contrat non trouvé", details: contractError },
        { status: 404 }
      );
    }

    if (!contract?.contract_pdf_filename) {
      // Diagnostic : renvoyer des infos sur le contrat
      return NextResponse.json(
        { 
          error: "PDF non trouvé pour ce contrat",
          debug: {
            contractId: params.id,
            contractNumber: contract?.contract_number,
            employeeName: contract?.employee_name,
            contract_pdf_filename: contract?.contract_pdf_filename,
            hasFilename: !!contract?.contract_pdf_filename
          }
        },
        { status: 404 }
      );
    }

    // 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!,
      },
    });

    // Génération de l'URL pré-signée (valide 1 heure)
    const command = new GetObjectCommand({
      Bucket: (process.env.AWS_S3_BUCKET || "odentas-docs").trim(),
      Key: `unsigned-contracts/${contract.contract_pdf_filename}`,
    });

    const signedUrl = await getSignedUrl(s3Client, command, { 
      expiresIn: 3600 // 1 heure
    });

    return NextResponse.json({
      pdfUrl: signedUrl,
      signedUrl: signedUrl, // Garde la compatibilité
      filename: contract.contract_pdf_filename
    });

  } catch (error) {
    console.error("Erreur lors de la génération de l'URL pré-signée:", error);
    return NextResponse.json(
      { 
        error: "Erreur interne du serveur", 
        details: error instanceof Error ? error.message : String(error) 
      },
      { status: 500 }
    );
  }
}