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

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

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

  const body = await request.json();
  const {
    status,
    title,
    description,
    location,
    locationPlaceId,
    locationLat,
    locationLng,
    startAt,
    endAt,
    categoryId,
    publicOverride
  } = body || {};

  if (status && ["APPROVED", "REJECTED"].includes(status)) {
    const event = await prisma.event.update({
      where: { id: context.params.id },
      data: { status }
    });

    return NextResponse.json(event);
  }

  if (!title || !startAt || !categoryId) {
    return NextResponse.json(
      { error: "Titel, Start und Kategorie sind erforderlich." },
      { status: 400 }
    );
  }

  const startDate = new Date(startAt);
  const endDate = endAt ? new Date(endAt) : null;
  const { publicAccessEnabled } = await getAccessSettings();
  const overrideValue =
    publicAccessEnabled && publicOverride !== undefined
      ? publicOverride === null || publicOverride === true || publicOverride === false
        ? publicOverride
        : null
      : undefined;

  const event = await prisma.event.update({
    where: { id: context.params.id },
    data: {
      title,
      description: description || null,
      location: location || null,
      locationPlaceId: locationPlaceId || null,
      locationLat: locationLat ? Number(locationLat) : null,
      locationLng: locationLng ? Number(locationLng) : null,
      startAt: startDate,
      endAt: endDate,
      category: { connect: { id: categoryId } },
      publicOverride: overrideValue
    }
  });

  return NextResponse.json(event);
}

export async function DELETE(
  _request: Request,
  context: { params: { id: string } }
) {
  const { session } = await requireSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

  await prisma.userViewItem.deleteMany({
    where: { eventId: context.params.id }
  });

  await prisma.event.delete({
    where: { id: context.params.id }
  });

  return NextResponse.json({ ok: true });
}
