import { NextRequest, NextResponse } from "next/server";

const API_KEY = process.env.GOOGLE_MAPS_API_KEY;

// A plain reverse geocode (no result_type filter) — used to resolve a
// device's current coordinates to a locality/district/state label for
// the device_name sent on login/register (see app/lib/deviceInfo.ts).
// Deliberately a separate route from /api/places/geocode, which is
// filtered to result_type=postal_code for a different feature
// (pincode autofill) and would often miss locality/district here.
export async function GET(request: NextRequest) {
  const lat = request.nextUrl.searchParams.get("lat");
  const lng = request.nextUrl.searchParams.get("lng");

  if (!lat || !lng) {
    return NextResponse.json({ result: null }, { status: 400 });
  }

  if (!API_KEY) {
    return NextResponse.json(
      { result: null, message: "Google Maps API key is not configured." },
      { status: 500 },
    );
  }

  try {
    const url = new URL("https://maps.googleapis.com/maps/api/geocode/json");
    url.searchParams.set("latlng", `${lat},${lng}`);
    url.searchParams.set("key", API_KEY);

    const response = await fetch(url.toString(), { cache: "no-store" });
    const data = await response.json();

    if (data.status !== "OK") {
      if (data.status !== "ZERO_RESULTS") {
        console.error("Reverse geocode error:", data.status, data.error_message);
      }
      return NextResponse.json({ result: null });
    }

    return NextResponse.json({ result: data.results?.[0] ?? null });
  } catch (error) {
    console.error("Reverse geocode proxy error:", error);
    return NextResponse.json({ result: null }, { status: 500 });
  }
}
