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 } = body;

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

    console.log(`[bulk-delete] Suppression de ${payslipIds.length} payslips:`, payslipIds);

    // Suppression groupée
    const { data, error } = await supabase
      .from("payslips")
      .delete()
      .in("id", payslipIds)
      .select("id");

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

    console.log(`[bulk-delete] ${data?.length || 0} payslips supprimées avec succès`);

    return NextResponse.json({ 
      success: true,
      deleted: data?.length || 0,
      payslips: data 
    });
  } catch (error) {
    console.error('[bulk-delete] Unexpected error:', error);
    return NextResponse.json({ error: "Erreur lors de la suppression" }, { status: 500 });
  }
}
