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 t0 = Date.now();
  const session = await getAuthSession();
  const hasTok = !!(session as { accessToken?: string } | null)?.accessToken;
  const err = (session as { error?: string } | null)?.error;
  console.log("[gis-search] in session=%s tok=%s err=%s", !!session, hasTok, err ?? "none");

  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 {
    const data = await gisApi.search(q, limit);
    console.log("[gis-search] ok q=%s dur=%dms", q, Date.now() - t0);
    return NextResponse.json(data);
  } catch (e) {
    if (e instanceof GisApiError) {
      console.log("[gis-search] gis-api %d %s", e.status, e.code);
      return NextResponse.json(
        { error: e.code, status: e.status },
        { status: e.status },
      );
    }
    const msg = e instanceof Error ? e.message : String(e);
    console.error("[gis-search] internal:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
