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

async function assertStaff(sb: ReturnType<typeof createSbServer>, userId: string) {
  const { data: me } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", userId)
    .maybeSingle();
  return !!me?.is_staff;
}

export async function POST(req: NextRequest) {
  const supabase = createSbServer();
  const { data: { user } } = await supabase.auth.getUser();
  
  if (!user) {
    return NextResponse.json({ error: "Non authentifié." }, { status: 401 });
  }
  
  const isStaff = await assertStaff(supabase, user.id);
  if (!isStaff) {
    return NextResponse.json({ error: "Accès réservé au staff." }, { status: 403 });
  }

  try {
    const body = await req.json();
    const { payslipIds, transferDone } = body;

    if (!Array.isArray(payslipIds) || payslipIds.length === 0) {
      return NextResponse.json({ error: "payslipIds requis" }, { status: 400 });
    }

    if (typeof transferDone !== 'boolean') {
      return NextResponse.json({ error: "transferDone doit être un booléen" }, { status: 400 });
    }

    // Mise à jour groupée
    const { data, error } = await supabase
      .from("payslips")
      .update({ transfer_done: transferDone })
      .in("id", payslipIds)
      .select("id, transfer_done");

    if (error) {
      console.error('[bulk-update-transfer] Error:', error);
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    return NextResponse.json({ payslips: data });
  } catch (error) {
    console.error('[bulk-update-transfer] Unexpected error:', error);
    return NextResponse.json({ error: "Erreur lors de la mise à jour" }, { status: 500 });
  }
}
