// POST /api/cf/order — Plan 003, Faza F.
//
// Server-side proxy to gisApi.enrichment.cf.create(). Used by parcel-sync's
// ePay UI when session.useGisAc === true. Legacy callers (flag=0) continue
// hitting /api/ancpi/order; this route MUST NOT replace it.
//
// Body: { nrCadastral: string, siruta?: string, gisFeatureId?: string }
//
// Responses:
//   200 → CfExtractRow (new order created or pending one returned)
//   409 → { error: "catalog_hit", existing: CfExtractRow } — forwarded verbatim
//   401 → no session
//   400 → invalid body / missing nrCadastral
//   Other → forwards GisApiError.status + .code
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";

interface CfOrderBody {
  nrCadastral?: string;
  siruta?: string;
  gisFeatureId?: string;
}

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

  let body: CfOrderBody;
  try {
    body = (await request.json()) as CfOrderBody;
  } catch {
    return NextResponse.json({ error: "invalid_body" }, { status: 400 });
  }

  const nrCadastral = body?.nrCadastral?.trim();
  if (!nrCadastral) {
    return NextResponse.json(
      { error: "missing_fields", required: ["nrCadastral"] },
      { status: 400 },
    );
  }

  try {
    const result = await gisApi.enrichment.cf.create({
      nrCadastral,
      siruta: body.siruta,
      gisFeatureId: body.gisFeatureId,
    });
    return NextResponse.json(result);
  } catch (err) {
    if (err instanceof GisApiError) {
      // Forward catalog_hit (409) verbatim so the UI can show the existing row.
      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-order] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
