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

const API_KEY = process.env.GOOGLE_MAPS_API_KEY;

// Fallback for getPlaceDetails() when a picked place's own
// address_components have no postal_code entry — reverse-geocoding the
// same lat/lng filtered to result_type=postal_code asks Google for the
// postal-code area that point falls inside, which it often has even
// when the more specific locality/village result doesn't carry one.
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("result_type", "postal_code");
    url.searchParams.set("key", API_KEY);

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

    if (data.status !== "OK") {
      // ZERO_RESULTS is expected for areas with no postal-code-level
      // geocode entry at all — not an error, just nothing to fill.
      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 });
  }
}
