import { NextResponse } from "next/server";

// GET /api/agency/cities?q=
// Proxies Google Places API (New) Autocomplete to return global city predictions
// formatted into our unified CityRef[] shape.
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const query = searchParams.get("q") || "";
  const apiKey =
    process.env.GOOGLE_PLACES_API_KEY ||
    process.env.GOOGLE_API_KEY ||
    process.env.CLOUD_API_KEY;

  if (!apiKey) {
    return NextResponse.json({ error: "GCP API Key missing" }, { status: 500 });
  }

  if (!query.trim()) {
    return NextResponse.json([]);
  }

  try {
    // Places API (New) Autocomplete Endpoint
    const url = "https://places.googleapis.com/v1/places:autocomplete";
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": apiKey,
      },
      body: JSON.stringify({
        input: query,
        includedPrimaryTypes: ["(cities)"], // restrict to cities/localities
      }),
    });

    if (!response.ok) {
      const errText = await response.text();
      console.error("Google Autocomplete Error:", errText);
      return NextResponse.json({ error: "Google API error" }, { status: 502 });
    }

    const data = await response.json();
    const suggestions = data.suggestions || [];

    // Map predictions to CityRef shape. Places (New) autocomplete returns structured format.
    const cities = suggestions.map(
      (s: { placePrediction: { text: { text: string }; placeId: string } }) => {
        const p = s.placePrediction;
        const text = p.text.text; // "Victoria, BC, Canada"
        const parts = text.split(",").map((x: string) => x.trim());

        const name = parts[0] || "";
        const region = parts[1] || "";
        const country = parts[parts.length - 1] || "";

        // Simple country code mapping
        let countryCode = "US";
        if (
          country.toLowerCase() === "canada" ||
          region.toLowerCase() === "bc" ||
          region.toLowerCase() === "on" ||
          region.toLowerCase() === "ab" ||
          region.toLowerCase() === "qc"
        ) {
          countryCode = "CA";
        } else if (
          country.toLowerCase() === "united kingdom" ||
          country.toLowerCase() === "uk" ||
          region.toLowerCase() === "england"
        ) {
          countryCode = "GB";
        } else if (
          country.toLowerCase() === "australia" ||
          region.toLowerCase() === "nsw" ||
          region.toLowerCase() === "vic"
        ) {
          countryCode = "AU";
        }

        return {
          id: p.placeId,
          name,
          region,
          country,
          countryCode,
        };
      },
    );

    return NextResponse.json(cities);
  } catch (err) {
    console.error("Autocomplete exception:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
