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

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

  const apiKeySetting = await prisma.setting.findUnique({
    where: { key: "google_places_api_key" }
  });
  const providerSetting = await prisma.setting.findUnique({
    where: { key: "geocoding_provider" }
  });
  const registrationSetting = await prisma.setting.findUnique({
    where: { key: "registration_enabled" }
  });

  const apiKey = apiKeySetting?.value || "";
  const provider =
    providerSetting?.value || (apiKey ? "google" : "osm");
  const registrationEnabled = registrationSetting?.value !== "false";

  return NextResponse.json({ apiKey, provider, registrationEnabled });
}

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

  if (!isSuperAdminSession(session)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const body = await request.json();
  const { apiKey, provider, registrationEnabled } = body || {};

  if (!provider || !["google", "osm"].includes(provider)) {
    return NextResponse.json({ error: "Provider erforderlich." }, { status: 400 });
  }

  if (provider === "google" && !apiKey) {
    return NextResponse.json({ error: "API-Key erforderlich." }, { status: 400 });
  }

  const apiKeyValue = provider === "google" ? apiKey : "";

  const apiKeySetting = await prisma.setting.upsert({
    where: { key: "google_places_api_key" },
    update: { value: apiKeyValue },
    create: { key: "google_places_api_key", value: apiKeyValue }
  });

  const providerSetting = await prisma.setting.upsert({
    where: { key: "geocoding_provider" },
    update: { value: provider },
    create: { key: "geocoding_provider", value: provider }
  });

  const registrationValue = registrationEnabled === false ? "false" : "true";
  await prisma.setting.upsert({
    where: { key: "registration_enabled" },
    update: { value: registrationValue },
    create: { key: "registration_enabled", value: registrationValue }
  });

  return NextResponse.json({
    apiKey: apiKeySetting.value,
    provider: providerSetting.value,
    registrationEnabled: registrationValue !== "false"
  });
}
