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 placeId = searchParams.get("placeId") || "";

  if (!placeId) {
    return NextResponse.json({ error: "PlaceId erforderlich." }, { status: 400 });
  }

  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({ error: "API-Key fehlt." }, { status: 400 });
    }

    const apiUrl = new URL("https://maps.googleapis.com/maps/api/place/details/json");
    apiUrl.searchParams.set("place_id", placeId);
    apiUrl.searchParams.set("fields", "geometry/location");
    apiUrl.searchParams.set("key", apiKeySetting.value);

    const response = await fetch(apiUrl.toString());
    if (!response.ok) {
      return NextResponse.json({ error: "Fehler beim Laden." }, { status: 400 });
    }

    const payload = await response.json();
    const location = payload?.result?.geometry?.location;
    return NextResponse.json({
      lat: location?.lat ?? null,
      lng: location?.lng ?? null
    });
  }

  const apiUrl = new URL("https://nominatim.openstreetmap.org/details");
  apiUrl.searchParams.set("place_id", placeId);
  apiUrl.searchParams.set("format", "json");

  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({ error: "Fehler beim Laden." }, { status: 400 });
  }

  const payload = await response.json();
  const coords = payload?.centroid?.coordinates;
  const lat = Array.isArray(coords) ? Number(coords[1]) : Number(payload?.lat);
  const lng = Array.isArray(coords) ? Number(coords[0]) : Number(payload?.lon);

  return NextResponse.json({
    lat: Number.isFinite(lat) ? lat : null,
    lng: Number.isFinite(lng) ? lng : null
  });
}
