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

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

  const views = await prisma.userView.findMany({
    where: { user: { email: session.user?.email || "" } },
    include: {
      items: { include: { event: true } },
      categories: { include: { category: true } },
      exclusions: true
    },
    orderBy: { createdAt: "desc" }
  });

  return NextResponse.json(views);
}

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

  const body = await request.json();
  const { name } = body || {};

  if (!name) {
    return NextResponse.json({ error: "Name erforderlich." }, { status: 400 });
  }

  const view = await prisma.userView.create({
    data: {
      name,
      token: randomUUID(),
      user: { connect: { email: session.user?.email || "" } }
    }
  });

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