// app/api/contrats/[id]/signed-pdf/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";
import { createClient } from "@supabase/supabase-js";
import { getS3SignedUrlIfExists } from "@/lib/aws-s3";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sb = createSbServer();

    // Vérification de l'authentification
    const { data: { user }, error: authError } = await sb.auth.getUser();
    if (authError || !user) {
      return NextResponse.json(
        { error: "Non autorisé" },
        { status: 401 }
      );
    }

    // Vérifier si l'utilisateur est staff
    const { data: staffData } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
    
    const isStaff = !!staffData?.is_staff;

    console.log(`[signed-pdf] 🔍 Fetching contract ${params.id} for ${isStaff ? 'staff' : 'client'} user`);

    // Récupération du contrat avec vérification d'accès via RLS
    // Si staff, utiliser le client admin pour bypass RLS
    let contract: any = null;
    let contractError: any = null;
    
    if (isStaff) {
      const admin = createClient(
        process.env.NEXT_PUBLIC_SUPABASE_URL || "",
        process.env.SUPABASE_SERVICE_ROLE_KEY || ""
      );
      const r = await admin
        .from("cddu_contracts")
        .select("id, contract_pdf_s3_key")
        .eq("id", params.id)
        .single();
      contract = r.data;
      contractError = r.error;
      console.log(`[signed-pdf] 📊 Admin query result:`, { contract, error: contractError?.message });
    } else {
      const r = await sb
        .from("cddu_contracts")
        .select("id, contract_pdf_s3_key")
        .eq("id", params.id)
        .single();
      contract = r.data;
      contractError = r.error;
      console.log(`[signed-pdf] 📊 Client query result:`, { contract, error: contractError?.message });
    }

    if (contractError || !contract) {
      console.log(`[signed-pdf] ❌ Contract not found or error:`, contractError?.message);
      return NextResponse.json(
        { error: "Contrat introuvable ou accès refusé" },
        { status: 404 }
      );
    }

    // Vérification de la présence de la clé S3
    if (!contract.contract_pdf_s3_key) {
      console.log(`[signed-pdf] ℹ️ No contract_pdf_s3_key for contract ${params.id}`);
      return NextResponse.json(
        { error: "Aucun contrat signé disponible", hasSignedPdf: false },
        { status: 404 }
      );
    }

    // Génération de l'URL pré-signée
    const signedUrl = await getS3SignedUrlIfExists(contract.contract_pdf_s3_key, 3600);
    
    if (!signedUrl) {
      return NextResponse.json(
        { error: "Contrat signé non trouvé dans le stockage", hasSignedPdf: false },
        { status: 404 }
      );
    }

    return NextResponse.json({
      signedUrl,
      hasSignedPdf: true,
      s3Key: contract.contract_pdf_s3_key
    });

  } 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" },
      { status: 500 }
    );
  }
}