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

export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const body = await req.json();
    
    // Validation des données
    if (typeof body.transfer_done !== "boolean") {
      return NextResponse.json(
        { error: "transfer_done must be a boolean" }, 
        { status: 400 }
      );
    }

    const sb = createSbServer();

    // Vérifier que la payslip existe et que l'utilisateur y a accès
    const { data: existing, error: fetchError } = await sb
      .from("payslips")
      .select("id, contract_id")
      .eq("id", id)
      .single();

    if (fetchError || !existing) {
      return NextResponse.json(
        { error: "payslip_not_found" }, 
        { status: 404 }
      );
    }

    // Mettre à jour le statut transfer_done
    const { data, error } = await sb
      .from("payslips")
      .update({ 
        transfer_done: body.transfer_done,
        updated_at: new Date().toISOString()
      })
      .eq("id", id)
      .select()
      .single();

    if (error) {
      console.error("Error updating payslip:", error);
      return NextResponse.json(
        { error: error.message }, 
        { status: 500 }
      );
    }

    return NextResponse.json(data);
  } catch (err: any) {
    console.error("Server error:", err);
    return NextResponse.json(
      { error: err?.message || "server_error" }, 
      { status: 500 }
    );
  }
}