import { NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

export async function POST(req: Request) {
  try {
    const sb = createSbServer();
    const { data: { user } } = await sb.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { data: me } = await sb.from("staff_users").select("is_staff").eq("user_id", user.id).maybeSingle();
    if (!me?.is_staff) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const { contractIds } = await req.json();

    if (!contractIds || !Array.isArray(contractIds) || contractIds.length === 0) {
      return NextResponse.json({ error: "Contract IDs are required" }, { status: 400 });
    }

    // Supprimer tous les contrats sélectionnés
    const { data: deletedContracts, error } = await sb
      .from("cddu_contracts")
      .delete()
      .in("id", contractIds)
      .select("id");

    if (error) {
      console.error("Error deleting contracts:", error);
      return NextResponse.json({ error: "Failed to delete contracts" }, { status: 500 });
    }

    return NextResponse.json({ 
      success: true, 
      deletedIds: deletedContracts?.map(c => c.id) || [],
      message: `${deletedContracts?.length || 0} contrat(s) supprimé(s)` 
    });

  } catch (err: any) {
    console.error("Bulk delete error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
