import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { S3Client, ListObjectsV2Command, 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 orgKey = searchParams.get('org_key');
    const docType = searchParams.get('doc_type');

    if (!orgKey || !docType) {
      return NextResponse.json({ error: "Paramètres manquants" }, { status: 400 });
    }

    // Lister les fichiers avec ce préfixe
    const prefix = `documents/${orgKey}/docs-generaux/${docType}_`;
    
    const listCommand = new ListObjectsV2Command({
      Bucket: BUCKET_NAME,
      Prefix: prefix,
    });

    const listResponse = await s3Client.send(listCommand);
    const files = listResponse.Contents || [];

    // Supprimer tous les fichiers trouvés
    const deletePromises = files.map(file => {
      if (file.Key) {
        const deleteCommand = new DeleteObjectCommand({
          Bucket: BUCKET_NAME,
          Key: file.Key,
        });
        return s3Client.send(deleteCommand);
      }
      return Promise.resolve();
    });

    await Promise.all(deletePromises);

    return NextResponse.json({ 
      success: true,
      deletedCount: files.length 
    });

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