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

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

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,
    publicAccessEnabled
  } = 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 }
  });

  const existing = await getSystemSettings();
  const nextPublicAccessEnabled =
    typeof publicAccessEnabled === "boolean"
      ? publicAccessEnabled
      : existing.publicAccessEnabled;

  const publicAccessValue = nextPublicAccessEnabled ? "true" : "false";
  await prisma.setting.upsert({
    where: { key: "public_access_enabled" },
    update: { value: publicAccessValue },
    create: { key: "public_access_enabled", value: publicAccessValue }
  });
  await prisma.setting.deleteMany({
    where: { key: { in: ["public_events_enabled", "anonymous_access_enabled"] } }
  });

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