import { NextResponse } from "next/server";
import { prisma } from "../../../../lib/prisma";
import { requireSession } from "../../../../lib/auth-helpers";

export async function GET(request: Request) {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const input = searchParams.get("input") || "";
  const countries = searchParams.get("countries") || "de,fr,ch,at";
  const countryList = countries
    .split(",")
    .map((entry) => entry.trim().toLowerCase())
    .filter(Boolean)
    .slice(0, 5);
  const countryParam = countryList.join(",");

  if (input.trim().length < 3) {
    return NextResponse.json({ predictions: [] });
  }

  const apiKeySetting = await prisma.setting.findUnique({
    where: { key: "google_places_api_key" }
  });
  const providerSetting = await prisma.setting.findUnique({
    where: { key: "geocoding_provider" }
  });
  const provider =
    providerSetting?.value || (apiKeySetting?.value ? "google" : "osm");

  if (provider === "google") {
    if (!apiKeySetting?.value) {
      return NextResponse.json({ predictions: [] });
    }

    const apiUrl = new URL("https://maps.googleapis.com/maps/api/place/autocomplete/json");
    apiUrl.searchParams.set("input", input);
    apiUrl.searchParams.set("key", apiKeySetting.value);
    apiUrl.searchParams.set("language", "de");
    apiUrl.searchParams.set("types", "geocode");
    if (countryParam) {
      apiUrl.searchParams.set("components", `country:${countryParam}`);
    }

    const response = await fetch(apiUrl.toString());
    if (!response.ok) {
      return NextResponse.json({ predictions: [] });
    }

    const payload = await response.json();
    return NextResponse.json({ predictions: payload.predictions || [] });
  }

  const apiUrl = new URL("https://nominatim.openstreetmap.org/search");
  apiUrl.searchParams.set("format", "jsonv2");
  apiUrl.searchParams.set("q", input);
  apiUrl.searchParams.set("addressdetails", "1");
  apiUrl.searchParams.set("limit", "5");
  apiUrl.searchParams.set("accept-language", "de");
  if (countryParam) {
    apiUrl.searchParams.set("countrycodes", countryParam);
  }

  const userAgent = process.env.NOMINATIM_USER_AGENT || "vereinskalender/1.0";
  const response = await fetch(apiUrl.toString(), {
    headers: { "User-Agent": userAgent }
  });
  if (!response.ok) {
    return NextResponse.json({ predictions: [] });
  }

  const payload = await response.json();
  const predictions = Array.isArray(payload)
    ? payload.map((item: any) => ({
        description: item.display_name,
        place_id: String(item.place_id)
      }))
    : [];
  return NextResponse.json({ predictions });
}
