import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

export const dynamic = "force-dynamic";

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const supabase = createRouteHandlerClient({ cookies });
    
    // Vérifier l'authentification
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    if (authError || !user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    // Vérifier que l'utilisateur est staff
    const { data: staffUser } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();

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

    // Récupérer l'avenant
    const { data: avenant, error } = await supabase
      .from("avenants")
      .select("pdf_s3_key, signed_pdf_s3_key, signature_status")
      .eq("id", id)
      .single();

    if (error || !avenant) {
      return NextResponse.json({ error: "Avenant non trouvé" }, { status: 404 });
    }

    // Utiliser signed_pdf_s3_key si disponible (PDF signé), sinon pdf_s3_key (PDF préliminaire)
    const pdfS3Key = avenant.signed_pdf_s3_key || avenant.pdf_s3_key;

    if (!pdfS3Key) {
      return NextResponse.json({ error: "PDF non trouvé" }, { status: 404 });
    }

    // Générer une URL signée
    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!,
      },
    });

    const presignedUrl = await getSignedUrl(
      s3Client,
      new GetObjectCommand({
        Bucket: "odentas-docs",
        Key: pdfS3Key,
      }),
      { expiresIn: 3600 } // 1 heure
    );

    return NextResponse.json({ presignedUrl });
  } catch (error) {
    console.error("Erreur génération URL PDF:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}
