import { NextResponse } from "next/server";
import { apiHandler, ApiError } from "@/lib/api";
import { requireAmapApiKey } from "@/lib/amap";

export const GET = apiHandler(async (req) => {
  const keywords = req.nextUrl.searchParams.get("keywords")?.trim();
  if (!keywords) return NextResponse.json([]);

  const apiKey = requireAmapApiKey();

  const location = req.nextUrl.searchParams.get("location");

  const url = new URL("https://restapi.amap.com/v3/assistant/inputtips");
  url.searchParams.set("key", apiKey);
  url.searchParams.set("keywords", keywords);
  url.searchParams.set("datatype", "poi");
  if (location) {
    url.searchParams.set("location", location);
  }

  let data;
  try {
    const res = await fetch(url.toString());
    data = await res.json();
  } catch {
    throw new ApiError("位置服务暂时不可用，请稍后重试", 503);
  }

  if (data.status !== "1" || !data.tips) return NextResponse.json([]);

  const suggestions = data.tips
    .filter((t: { location?: string }) => t.location && t.location !== "")
    .slice(0, 8)
    .map((t: { id: string; name: string; district?: string; address?: string; location: string }) => {
      const [lng, lat] = t.location.split(",").map(Number);
      return {
        id: t.id,
        name: t.name,
        district: t.district || "",
        address: t.address || "",
        lat,
        lng,
      };
    });

  return NextResponse.json(suggestions);
});
