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 ||
      ""
    );
  }
}

function isValidKey(key: string) {
  if (key.length < 20) return false;
  if (key.startsWith("eyJ")) {
    const parts = key.split(".");
    if (parts.length !== 3 || parts.some((p) => !p)) return false;
  }
  return true;
}

export async function GET(req: NextRequest) {
  const text = req.nextUrl.searchParams.get("text")?.trim() || "";
  // Map.ir برای کمتر از ۲ کاراکتر 404 می‌دهد
  if (text.length < 2) {
    return NextResponse.json({ value: [], "odata.count": 0 });
  }

  const key = await getMapKey();
  if (!isValidKey(key)) {
    return NextResponse.json({ value: [], error: "invalid_map_key" });
  }

  const params = new URLSearchParams({ text });
  const lat = req.nextUrl.searchParams.get("lat");
  const lon = req.nextUrl.searchParams.get("lon");
  if (lat) params.set("lat", lat);
  if (lon) params.set("lon", lon);

  try {
    const res = await fetch(`https://map.ir/search/v2/autocomplete?${params}`, {
      headers: { "x-api-key": key, "Mapir-SDK": "reactjs" },
      cache: "no-store",
    });
    const data = await res.json().catch(() => ({ value: [] }));
    // همیشه 200 تا کنسول مرورگر پر از 404 نشود
    if (!res.ok) {
      return NextResponse.json({ value: [], "odata.count": 0 });
    }
    return NextResponse.json(data);
  } catch {
    return NextResponse.json({ value: [], error: "map_unreachable" });
  }
}
