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 email = session.user?.email || "";
  const existing = await prisma.userView.findFirst({
    where: { user: { email } },
    include: {
      items: { include: { event: true } },
      categories: { include: { category: true } },
      exclusions: true
    }
  });

  if (existing) {
    return NextResponse.json(existing);
  }

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

  const categories = await prisma.category.findMany({
    select: { id: true }
  });

  if (categories.length > 0) {
    await prisma.userViewCategory.createMany({
      data: categories.map((category) => ({
        viewId: view.id,
        categoryId: category.id
      }))
    });
  }

  const hydrated = await prisma.userView.findUnique({
    where: { id: view.id },
    include: {
      items: { include: { event: true } },
      categories: { include: { category: true } },
      exclusions: true
    }
  });

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

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

  const body = await request.json();
  const icalPastDays = Number(body?.icalPastDays);
  if (!Number.isFinite(icalPastDays) || icalPastDays < 0 || icalPastDays > 365) {
    return NextResponse.json(
      { error: "iCal-Rückblick ist ungültig." },
      { status: 400 }
    );
  }

  const email = session.user?.email || "";
  const view = await prisma.userView.findFirst({
    where: { user: { email } }
  });

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

  const updated = await prisma.userView.update({
    where: { id: view.id },
    data: { icalPastDays: Math.floor(icalPastDays) }
  });

  return NextResponse.json(updated);
}
