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

interface AmapPoiV5 {
  id: string;
  name: string;
  address?: string;
  location?: string;
  type?: string;
  business?: {
    rating?: string;
    cost?: string;
    tel?: string;
  };
}

export const GET = apiHandler(async (req) => {
  const keywords = req.nextUrl.searchParams.get("keywords")?.trim();
  if (!keywords) throw new ApiError("keywords 不能为空");

  const city = req.nextUrl.searchParams.get("city")?.trim();
  const types = req.nextUrl.searchParams.get("types")?.trim();

  const apiKey = requireAmapApiKey();

  const url = new URL("https://restapi.amap.com/v5/place/text");
  url.searchParams.set("key", apiKey);
  url.searchParams.set("keywords", keywords);
  url.searchParams.set("show_fields", "business");
  url.searchParams.set("page_size", "10");

  if (city) url.searchParams.set("region", city);
  if (types) url.searchParams.set("types", types);

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

  if (data.status !== "1" || !data.pois?.length) {
    return NextResponse.json([]);
  }

  const results = data.pois
    .filter((poi: AmapPoiV5) => poi.location)
    .map((poi: AmapPoiV5) => {
      const [lng, lat] = (poi.location ?? "0,0").split(",").map(Number);
      const ratingStr = poi.business?.rating;
      const rating = ratingStr && ratingStr !== "[]" ? parseFloat(ratingStr) || null : null;
      const costStr = poi.business?.cost;
      const cost = costStr && costStr !== "[]" && costStr !== "0" ? Number(costStr) : null;

      return {
        id: poi.id,
        name: poi.name,
        address: poi.address || "",
        lat,
        lng,
        rating,
        cost,
      };
    });

  return NextResponse.json(results);
});
