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().catch(() => null);
    if (!body || !body.id) return NextResponse.json({ error: "Bad Request" }, { status: 400 });

    // Only allow patching a limited set of fields on cddu_contracts
    const allowed: any = {};
    [
      "contract_number",
      "employee_name",
      "structure",
      "org_id",
      "type_de_contrat",
      "start_date",
      "end_date",
      "brut",
      "notes",
      "etat_de_la_demande",
    ].forEach((k) => {
      if (body[k] !== undefined) allowed[k] = body[k];
    });
    allowed.id = body.id;

  const { error } = await sb.from("cddu_contracts").upsert(allowed, { onConflict: "id" });
    if (error) return NextResponse.json({ error: error.message }, { status: 500 });

    return NextResponse.json({ ok: true });
  } catch (err: any) {
    console.error(err);
    return NextResponse.json({ error: "Internal" }, { status: 500 });
  }
}
