// GET /api/cf/orders — Plan 003, Faza F.
//
// Server-side proxy to gisApi.enrichment.cf.list(). RLS-filtered on the
// gis-api side — only the caller's own CfExtract rows are returned.
//
// Query params: ?limit=&offset=&status=
//
// Response shape (forwarded verbatim from gis-api):
//   { total, limit, offset, rows: CfExtractRow[] }
import { NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth/require-auth";
import { gisApi, GisApiError } from "@/lib/gis-api-client";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const session = await getAuthSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const limitRaw = Number(searchParams.get("limit") ?? "50");
  const offsetRaw = Number(searchParams.get("offset") ?? "0");
  const status = searchParams.get("status")?.trim() || undefined;

  const limit =
    Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 200) : 50;
  const offset = Number.isFinite(offsetRaw) && offsetRaw >= 0 ? offsetRaw : 0;

  try {
    return NextResponse.json(
      await gisApi.enrichment.cf.list({ limit, offset, status }),
    );
  } catch (err) {
    if (err instanceof GisApiError) {
      return NextResponse.json(
        { error: err.code, status: err.status, body: err.body },
        { status: err.status },
      );
    }
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[cf-orders] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
