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, dpaeStatus } = await req.json();

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

    if (!dpaeStatus || !['À faire', 'Faite'].includes(dpaeStatus)) {
      return NextResponse.json({ error: "Valid DPAE status is required" }, { status: 400 });
    }

    // Mettre à jour tous les contrats sélectionnés
    const { data: updatedContracts, error } = await sb
      .from("cddu_contracts")
      .update({ dpae: dpaeStatus })
      .in("id", contractIds)
      .select("id, dpae");

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

    return NextResponse.json({ 
      success: true, 
      contracts: updatedContracts,
      message: `${updatedContracts?.length || 0} contrat(s) mis à jour` 
    });

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