import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { apiHandler, ApiError, requireUserId } from "@/lib/api";

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

  requireUserId(userId);
  if (!code || typeof code !== "string") throw new ApiError("请输入房间号");

  const room = await prisma.blindBoxRoom.findUnique({
    where: { code: code.trim().toUpperCase() },
  });
  if (!room) throw new ApiError("房间不存在，请检查房间号", 404);

  const existing = await prisma.blindBoxMember.findUnique({
    where: { roomId_userId: { roomId: room.id, userId } },
  });
  if (existing) {
    return NextResponse.json({
      id: room.id,
      code: room.code,
      name: room.name,
      alreadyMember: true,
    });
  }

  await prisma.blindBoxMember.create({
    data: { roomId: room.id, userId },
  });

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