import { NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth/require-auth";
import { gisApi, GisApiError, type ParcelRefBody } from "@/lib/gis-api-client";

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

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

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

  if (!body?.siruta || !body?.cadastralRef) {
    return NextResponse.json(
      { error: "missing_fields", required: ["siruta", "cadastralRef"] },
      { status: 400 },
    );
  }

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