import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { getStaffSession } from "@/lib/staff-session";
import crypto from "crypto";

const ADMIN_ROLES = ["ADMIN", "SUPER_ADMIN"];

export async function POST(request: NextRequest) {
  const user = await getStaffSession();
  if (!user || !ADMIN_ROLES.includes(user.role)) {
    return NextResponse.json(
      { error: "Admin role required to create preview tokens" },
      { status: 403 },
    );
  }

  const body = await request.json().catch(() => ({}));
  const scopes: string[] = Array.isArray(body.scopes) ? body.scopes : ["all"];
  const expiresInMinutes =
    typeof body.expiresInMinutes === "number" ? body.expiresInMinutes : 60;
  const expiresAt = new Date(Date.now() + expiresInMinutes * 60 * 1000);

  const token = crypto.randomUUID();

  const record = await prisma.preview_tokens.create({
    data: {
      token,
      scopes,
      expiresAt,
      createdBy: user.id,
    },
  });

  return NextResponse.json({
    token: record.token,
    expiresAt: record.expiresAt,
    scopes: record.scopes,
  });
}
