// app/api/staff/payslips/last-pay-number/route.ts
import { createSbServer } from "@/lib/supabaseServer";
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  try {
    const sb = createSbServer();
    
    // Vérifier l'authentification
    const { data: { user } } = await sb.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Vérifier que c'est un staff
    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 searchParams = request.nextUrl.searchParams;
    const contractId = searchParams.get("contract_id");

    if (!contractId) {
      return NextResponse.json({ error: "contract_id requis" }, { status: 400 });
    }

    // Récupérer le dernier numéro de paie pour ce contrat
    const { data: payslips, error } = await sb
      .from("payslips")
      .select("pay_number")
      .eq("contract_id", contractId)
      .order("pay_number", { ascending: false })
      .limit(1);

    if (error) {
      console.error("[GET /api/staff/payslips/last-pay-number] Database error:", error);
      return NextResponse.json({ error: "Database error" }, { status: 500 });
    }

    const lastPayNumber = payslips && payslips.length > 0 ? payslips[0].pay_number : 0;

    return NextResponse.json({ last_pay_number: lastPayNumber || 0 });
  } catch (error) {
    console.error("[GET /api/staff/payslips/last-pay-number] Error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
