import { NextResponse } from "next/server";
import {
	getGoogleMapsLocationCapability,
	getGoogleMapsServerApiKey,
	mapGooglePlacesSuggestions,
} from "@/lib/google-maps";

const AUTOCOMPLETE_FIELD_MASK = [
	"suggestions.placePrediction.place",
	"suggestions.placePrediction.placeId",
	"suggestions.placePrediction.text.text",
	"suggestions.placePrediction.structuredFormat.mainText.text",
	"suggestions.placePrediction.structuredFormat.secondaryText.text",
].join(",");

export async function GET(request: Request) {
	const capability = getGoogleMapsLocationCapability();
	if (!capability.enabled) {
		return NextResponse.json({ suggestions: [] }, { status: 503 });
	}

	const apiKey = getGoogleMapsServerApiKey();
	if (!apiKey) {
		return NextResponse.json({ suggestions: [] }, { status: 503 });
	}

	const { searchParams } = new URL(request.url);
	const input = searchParams.get("input")?.trim();
	const sessionToken = searchParams.get("sessionToken")?.trim();

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

	const response = await fetch(
		"https://places.googleapis.com/v1/places:autocomplete",
		{
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"X-Goog-Api-Key": apiKey,
				"X-Goog-FieldMask": AUTOCOMPLETE_FIELD_MASK,
			},
			body: JSON.stringify({
				input,
				sessionToken: sessionToken || undefined,
			}),
		},
	);

	if (!response.ok) {
		return NextResponse.json({ suggestions: [] }, { status: 502 });
	}

	const payload = (await response.json()) as Parameters<
		typeof mapGooglePlacesSuggestions
	>[0];
	return NextResponse.json({
		suggestions: mapGooglePlacesSuggestions(payload),
	});
}
