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

async function ensureOwner(viewId: string, email: string) {
  const view = await prisma.userView.findFirst({
    where: { id: viewId, user: { email } }
  });
  return view;
}

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

  const email = session.user?.email || "";
  const view = await ensureOwner(context.params.id, email);
  if (!view) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const body = await request.json();
  const { eventId } = body || {};
  if (!eventId) {
    return NextResponse.json({ error: "Event erforderlich." }, { status: 400 });
  }

  const event = await prisma.event.findUnique({
    where: { id: eventId },
    select: { categoryId: true }
  });

  if (!event) {
    return NextResponse.json({ error: "Event nicht gefunden." }, { status: 404 });
  }

  await prisma.userViewExclusion.deleteMany({
    where: { viewId: view.id, eventId }
  });

  if (event.categoryId) {
    const subscribed = await prisma.userViewCategory.findUnique({
      where: {
        viewId_categoryId: { viewId: view.id, categoryId: event.categoryId }
      }
    });
    if (subscribed) {
      return NextResponse.json({ ok: true }, { status: 201 });
    }
  }

  await prisma.userViewItem.upsert({
    where: { viewId_eventId: { viewId: view.id, eventId } },
    update: {},
    create: { viewId: view.id, eventId }
  });

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

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

  const email = session.user?.email || "";
  const view = await ensureOwner(context.params.id, email);
  if (!view) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  const body = await request.json();
  const { eventId } = body || {};
  if (!eventId) {
    return NextResponse.json({ error: "Event erforderlich." }, { status: 400 });
  }

  const event = await prisma.event.findUnique({
    where: { id: eventId },
    select: { categoryId: true }
  });

  if (!event) {
    return NextResponse.json({ error: "Event nicht gefunden." }, { status: 404 });
  }

  if (event.categoryId) {
    const subscribed = await prisma.userViewCategory.findUnique({
      where: {
        viewId_categoryId: { viewId: view.id, categoryId: event.categoryId }
      }
    });
    if (subscribed) {
      await prisma.userViewExclusion.upsert({
        where: { viewId_eventId: { viewId: view.id, eventId } },
        update: {},
        create: { viewId: view.id, eventId }
      });
      return NextResponse.json({ ok: true });
    }
  }

  await prisma.userViewItem.deleteMany({
    where: { viewId: view.id, eventId }
  });

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