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

export const dynamic = "force-dynamic";

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

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const cookieStore = cookies();
    const supabase = createRouteHandlerClient({ cookies: () => cookieStore });

    // Vérifier l'authentification staff
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    
    if (authError || !user) {
      console.error("[NAA Presigned URL] Auth error:", authError);
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    console.log("[NAA Presigned URL] User authenticated:", user.id);
    if (!user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    console.log("[NAA Presigned URL] User authenticated:", user.id);

    const { data: staffUser, error: staffError } = await supabase
      .from("staff_users")
      .select("user_id")
      .eq("user_id", user.id)
      .single();

    if (staffError || !staffUser) {
      console.error("[NAA Presigned URL] Staff check failed:", staffError);
      return NextResponse.json({ error: "Accès non autorisé" }, { status: 403 });
    }

    console.log("[NAA Presigned URL] Staff user found:", staffUser.user_id);

    // Récupérer le document NAA
    const { data: naaDoc, error } = await supabase
      .from("naa_documents")
      .select("s3_key")
      .eq("id", params.id)
      .single();

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

    if (!naaDoc.s3_key) {
      return NextResponse.json({ error: "Aucun fichier associé" }, { status: 404 });
    }

    // Générer l'URL présignée (valide 1 heure)
    const bucketName = process.env.AWS_S3_BUCKET_NAME || "odentas-docs";
    const getObjectCommand = new GetObjectCommand({
      Bucket: bucketName,
      Key: naaDoc.s3_key,
    });

    const presignedUrl = await getSignedUrl(s3Client, getObjectCommand, { expiresIn: 3600 });

    return NextResponse.json({ presigned_url: presignedUrl });

  } catch (error: any) {
    console.error("Error generating presigned URL:", error);
    return NextResponse.json(
      { error: error.message || "Erreur serveur" },
      { status: 500 }
    );
  }
}
