import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { S3Client, DeleteObjectCommand } from "@aws-sdk/client-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 || "",
  },
});

const BUCKET_NAME = (process.env.AWS_S3_BUCKET || "odentas-docs").trim();

export async function DELETE(req: NextRequest) {
  try {
    const sb = createRouteHandlerClient({ cookies });
    
    // Vérifier que l'utilisateur est staff
    const { data: { user } } = await sb.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

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

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

    const { searchParams } = new URL(req.url);
    const docId = searchParams.get('doc_id');

    if (!docId) {
      return NextResponse.json({ error: "doc_id manquant" }, { status: 400 });
    }

    // Récupérer le document pour obtenir le storage_path
    const { data: doc, error: fetchError } = await sb
      .from('documents')
      .select('storage_path')
      .eq('id', docId)
      .single();

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

    // Supprimer de S3
    if (doc.storage_path) {
      const deleteCommand = new DeleteObjectCommand({
        Bucket: BUCKET_NAME,
        Key: doc.storage_path,
      });
      await s3Client.send(deleteCommand);
    }

    // Supprimer de la base de données
    const { error: deleteError } = await sb
      .from('documents')
      .delete()
      .eq('id', docId);

    if (deleteError) {
      console.error('Erreur suppression Supabase:', deleteError);
      return NextResponse.json({ error: "Erreur base de données" }, { status: 500 });
    }

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

  } catch (error) {
    console.error("Erreur suppression document comptable:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}
