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,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getAuthSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: "missing_id" }, { status: 400 });
  }

  try {
    const data = await gisApi.parcela.get(id);
    const enr =
      (data as { enrichment?: Record<string, unknown> } | null)?.enrichment ?? null;
    console.log(
      "[gis-parcela] id=%s has_enrich=%s keys=%d",
      id.slice(0, 8),
      !!enr,
      enr ? Object.keys(enr).length : 0,
    );
    return NextResponse.json(data);
  } catch (err) {
    if (err instanceof GisApiError) {
      console.log("[gis-parcela] gis-api %d %s", err.status, err.code);
      return NextResponse.json(
        { error: err.code, status: err.status },
        { status: err.status },
      );
    }
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[gis-parcela] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
