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

export async function GET(req: NextRequest) {
  try {
    const url = new URL(req.url);
    const contractId = url.searchParams.get("contract_id");
    if (!contractId) {
      return NextResponse.json({ error: "missing_contract_id" }, { status: 400 });
    }

    const sb = createSbServer();
    // Query with the server-side Supabase client so RLS sees the user's JWT from cookies
    let q = sb.from("payslips").select("*").eq("contract_id", contractId);

    // If an active org header is present, apply it (some policies expect this header to scope data)
    const activeOrg = req.headers.get("x-active-org-id") || undefined;
    if (activeOrg) q = q.eq("organization_id", activeOrg);

    const { data, error } = await q.order("period_start", { ascending: false });

    if (error) {
      // If it's an RLS/access problem, return 403 so client can handle it
      return NextResponse.json({ error: error.message }, { status: 403 });
    }

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