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 q = searchParams.get("q")?.trim() ?? "";
  const limitRaw = Number(searchParams.get("limit") ?? "20");
  const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 100) : 20;

  if (q.length < 2) {
    return NextResponse.json({ q, uats: [], features: [] });
  }

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