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

    if (!updates || !Array.isArray(updates) || updates.length === 0) {
      return NextResponse.json({ error: "Updates array is required" }, { status: 400 });
    }

    // Valider que chaque update a un id et un joursTravail
    for (const update of updates) {
      if (!update.id || typeof update.joursTravail !== 'string') {
        return NextResponse.json({ error: "Each update must have id and joursTravail" }, { status: 400 });
      }
    }

    // Mettre à jour chaque contrat individuellement
    const updatedContracts = [];
    for (const update of updates) {
      const { data, error } = await sb
        .from("cddu_contracts")
        .update({ 
          jours_travail: update.joursTravail,
          jours_travail_non_artiste: update.joursTravail
        })
        .eq("id", update.id)
        .select("id, jours_travail, jours_travail_non_artiste");

      if (error) {
        console.error(`Error updating contract ${update.id}:`, error);
        continue;
      }

      if (data && data.length > 0) {
        updatedContracts.push(data[0]);
      }
    }

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

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