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

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

    if (!etatPaie || !['À traiter', 'En cours', 'Traitée'].includes(etatPaie)) {
      return NextResponse.json({ error: "Valid payroll status is required" }, { status: 400 });
    }

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

    if (error) {
      console.error("Error updating payroll status:", 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 payroll status update error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
