import { NextRequest, NextResponse } from "next/server";
import { BASE_URL } from "@/config/global";

async function getMapKey() {
  try {
    const res = await fetch(`${BASE_URL}v1/rest/settings`, { next: { revalidate: 60 } });
    if (!res.ok) return "";
    const json = await res.json();
    const list = Array.isArray(json?.data) ? json.data : [];
    const row = list.find((s: { key?: string }) => s?.key === "google_map_key");
    return String(row?.value || "").trim();
  } catch {
    return (
      process.env.NEXT_PUBLIC_MAP_IR_KEY ||
      process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY ||
      ""
    );
  }
}

export async function GET(req: NextRequest) {
  const lat = req.nextUrl.searchParams.get("lat");
  const lon = req.nextUrl.searchParams.get("lon");
  if (!lat || !lon) {
    return NextResponse.json({ address: "" }, { status: 400 });
  }

  const key = await getMapKey();
  if (!key) {
    return NextResponse.json({ address: "" }, { status: 400 });
  }

  try {
    const res = await fetch(`https://map.ir/reverse?lat=${lat}&lon=${lon}`, {
      headers: { "x-api-key": key, "Mapir-SDK": "reactjs" },
      cache: "no-store",
    });
    if (!res.ok) return NextResponse.json({ address: "" }, { status: res.status });
    const data = await res.json();
    const address =
      data?.address_compact ||
      data?.relative_address ||
      data?.address ||
      data?.neighbourhood ||
      "";
    return NextResponse.json({ address, ...data });
  } catch {
    return NextResponse.json({ address: "" }, { status: 502 });
  }
}
