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

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const input = (searchParams.get("input") ?? "").trim();

  if (!input) {
    return NextResponse.json({ predictions: [] });
  }

  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 {
    // Use Places API (New) autocomplete endpoint
    const googleUrl = "https://places.googleapis.com/v1/places:autocomplete";

    const res = await fetch(googleUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": key,
      },
      // Avoid caching user-typed queries
      cache: "no-store",
      body: JSON.stringify({
        input,
        languageCode: "en",
      }),
    });

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

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

    const predictions =
      data?.suggestions
        ?.map((s: any) => {
          const p = s.placePrediction || s.queryPrediction;
          if (!p) return null;

          const description =
            p.text?.text ||
            p.structuredFormat?.mainText?.text ||
            p.structuredFormat?.secondaryText?.text;

          const placeId = p.placeId || p.place;
          const types: string[] = p.types || [];

          if (!description || !placeId) return null;

          return {
            description,
            place_id: placeId,
            types,
          };
        })
        .filter(Boolean) ?? [];

    return NextResponse.json({ predictions });
  } catch (e) {
    return NextResponse.json(
      { message: "Unexpected error fetching Google Places suggestions." },
      { status: 500 }
    );
  }
}
