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

export const GET = apiHandler(async (req) => {
  const lat = req.nextUrl.searchParams.get("lat");
  const lng = req.nextUrl.searchParams.get("lng");

  if (!lat || !lng) throw new ApiError("lat and lng are required");

  const apiKey = requireAmapApiKey();

  const url = new URL("https://restapi.amap.com/v3/geocode/regeo");
  url.searchParams.set("key", apiKey);
  url.searchParams.set("location", `${lng},${lat}`);
  url.searchParams.set("extensions", "base");

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

  if (data.status !== "1" || !data.regeocode) {
    return NextResponse.json({ name: null });
  }

  const comp = data.regeocode.addressComponent;
  const district = comp?.district || comp?.city || "";
  const township = comp?.township || "";
  const neighborhood = comp?.neighborhood?.name || "";

  const name = [district, township, neighborhood]
    .filter(Boolean)
    .join(" ")
    .trim();

  return NextResponse.json({
    name: name || data.regeocode.formatted_address || null,
    formatted: data.regeocode.formatted_address || null,
  });
});
