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

const DEFAULT_APP_NAME = "Vereinskalender";

export async function GET() {
  const setting = await prisma.setting.findUnique({
    where: { key: "app_name" }
  });
  return NextResponse.json({ name: setting?.value || DEFAULT_APP_NAME });
}

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 name = String(body?.name || "").trim();
  if (!name) {
    return NextResponse.json({ error: "Name erforderlich." }, { status: 400 });
  }
  if (name.length > 60) {
    return NextResponse.json({ error: "Name ist zu lang." }, { status: 400 });
  }

  await prisma.setting.upsert({
    where: { key: "app_name" },
    update: { value: name },
    create: { key: "app_name", value: name }
  });

  return NextResponse.json({ name });
}
