import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { generateUniqueRoomCode } from "@/lib/blindbox";
import { apiHandler, requireUserId, requireUser } from "@/lib/api";
import { validateRoomName } from "@/lib/validation";

export const POST = apiHandler(async (req) => {
  const { userId, name } = await req.json();

  requireUserId(userId);

  const roomName = validateRoomName(name);

  await requireUser(userId);

  const code = await generateUniqueRoomCode();

  const room = await prisma.blindBoxRoom.create({
    data: {
      code,
      name: roomName,
      creatorId: userId,
      members: { create: { userId } },
    },
  });

  return NextResponse.json(
    { id: room.id, code: room.code, name: room.name },
    { status: 201 },
  );
});
