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

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

  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 },
  );
});
