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

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

    // Groupe par date pour minimiser les appels
    const groups: Record<string, string[]> = {};
    for (const u of updates) {
      const id = u.id;
      // accept null or empty to clear the date
      const date = u.date === null || u.date === undefined || u.date === '' ? '__NULL__' : String(u.date);
      if (!groups[date]) groups[date] = [];
      groups[date].push(id);
    }

    let allUpdated: Array<{ id: string; date_signature: string | null }> = [];

    for (const key of Object.keys(groups)) {
      const ids = groups[key];
      const dateValue = key === '__NULL__' ? null : key;

      const { data: updated, error } = await sb
        .from('cddu_contracts')
        .update({ date_signature: dateValue })
        .in('id', ids)
        .select('id, date_signature');

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

      if (updated) {
        allUpdated = allUpdated.concat(updated as any);
      }
    }

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

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