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

export async function POST(req: Request, { params }: { params: { id: string } }) {
  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 id = params.id;
    const body = await req.json().catch(() => ({}));

    // Minimal payslip creation — adjust fields to your schema
    const toInsert: any = {
      contract_id: id,
      period_start: body.period_start || new Date().toISOString().slice(0,10),
      period_end: body.period_end || new Date().toISOString().slice(0,10),
      period_month: body.period_month || new Date().toISOString().slice(0,7),
      gross_amount: body.gross_amount ?? null,
      net_amount: body.net_amount ?? null,
      processed: false,
      created_at: new Date().toISOString(),
    };

    const { data, error } = await sb.from('payslips').insert(toInsert).select().maybeSingle();
    if (error) return NextResponse.json({ error: error.message }, { status: 500 });
    return NextResponse.json(data);
  } catch (err: any) {
    console.error(err);
    return NextResponse.json({ error: 'Internal' }, { status: 500 });
  }
}
