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

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

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

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

  const updated = await prisma.userView.update({
    where: { id: view.id },
    data: { token: randomUUID() }
  });

  return NextResponse.json({ id: updated.id, token: updated.token });
}
