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

  if (!lat || !lng) {
    return NextResponse.json({ error: "Koordinaten 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/geocode/json");
    apiUrl.searchParams.set("latlng", `${lat},${lng}`);
    apiUrl.searchParams.set("key", apiKeySetting.value);
    apiUrl.searchParams.set("language", "de");

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

    const payload = await response.json();
    const result = payload?.results?.[0];
    return NextResponse.json({
      label: result?.formatted_address || null,
      placeId: result?.place_id || null
    });
  }

  const apiUrl = new URL("https://nominatim.openstreetmap.org/reverse");
  apiUrl.searchParams.set("format", "jsonv2");
  apiUrl.searchParams.set("lat", lat);
  apiUrl.searchParams.set("lon", lng);
  apiUrl.searchParams.set("addressdetails", "1");

  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();
  return NextResponse.json({
    label: payload?.display_name || null,
    placeId: payload?.place_id ? String(payload.place_id) : null
  });
}
