// GET /api/cf/catalog?nrCadastral=... — Plan 003, Faza F.
//
// Wraps gisApi.enrichment.catalog(nrCadastral). Lets the UI check if a
// fresh CF extract already exists in the shared catalog before placing a
// new order (avoids duplicate spend on the user's ePay credits).
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 nrCadastral = searchParams.get("nrCadastral")?.trim();
  if (!nrCadastral) {
    return NextResponse.json(
      { error: "missing_fields", required: ["nrCadastral"] },
      { status: 400 },
    );
  }

  try {
    return NextResponse.json(await gisApi.enrichment.catalog(nrCadastral));
  } 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-catalog] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
