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

// GET /api/google/places/details?placeId=...
export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const placeId = (searchParams.get("placeId") ?? "").trim();

  if (!placeId) {
    return NextResponse.json(
      { message: "placeId query parameter is required." },
      { status: 400 }
    );
  }

  const key =
    process.env.GOOGLE_MAPS_API_KEY ||
    process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;

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

  try {
    // Places API (New) details endpoint
    const encodedId = encodeURIComponent(placeId);
    const fields = [
      "displayName",
      "formattedAddress",
      "types",
      "addressComponents",
      "location",
    ].join(",");

    const url = `https://places.googleapis.com/v1/places/${encodedId}?fields=${encodeURIComponent(
      fields
    )}`;

    const res = await fetch(url, {
      method: "GET",
      headers: {
        "X-Goog-Api-Key": key,
      },
      cache: "no-store",
    });

    const data = (await res.json()) as any;

    if (!res.ok) {
      return NextResponse.json(
        {
          message:
            data?.error?.message || "Failed to fetch Google Place details.",
        },
        { status: res.status }
      );
    }

    const addressComponents: any[] = data?.addressComponents ?? [];

    const pickComponent = (type: string) =>
      addressComponents.find((c) => (c.types || []).includes(type));

    const localityComp =
      pickComponent("sublocality") ||
      pickComponent("sublocality_level_1") ||
      pickComponent("neighborhood");
    const cityComp = pickComponent("locality");
    const stateComp = pickComponent("administrative_area_level_1");
    const countryComp = pickComponent("country");
    const postalCodeComp = pickComponent("postal_code");

    const parsedAddress = {
      locality: localityComp?.longText ?? localityComp?.shortText ?? null,
      city: cityComp?.longText ?? cityComp?.shortText ?? null,
      state: stateComp?.longText ?? stateComp?.shortText ?? null,
      country: countryComp?.longText ?? countryComp?.shortText ?? null,
      postalCode: postalCodeComp?.longText ?? postalCodeComp?.shortText ?? null,
      latitude: data?.location?.latitude ?? null,
      longitude: data?.location?.longitude ?? null,
    };

    const result = {
      name: data?.displayName?.text ?? null,
      formattedAddress: data?.formattedAddress ?? null,
      types: data?.types ?? [],
      addressComponents,
      parsedAddress,
    };

    return NextResponse.json(result);
  } catch (e) {
    return NextResponse.json(
      { message: "Unexpected error fetching Google Place details." },
      { status: 500 }
    );
  }
}
