import { NextResponse } from "next/server";
import { atomicUpdateRoom } from "@/lib/store";
import { notify } from "@/lib/roomEvents";
import { apiHandler, ApiError, requireUserId } from "@/lib/api";

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

  requireUserId(userId);

  const updated = await atomicUpdateRoom(id, (data) => {
    if (data.kickedUsers.includes(userId)) {
      throw new ApiError("你已被移出该房间", 403);
    }
    if (data.locked && !data.users.includes(userId)) {
      throw new ApiError("房间已锁定，无法加入", 403);
    }
    if (!data.users.includes(userId)) {
      data.users.push(userId);
    }
    return data;
  });

  if (!updated) throw new ApiError("房间不存在或已过期", 404);

  notify(id);

  return NextResponse.json({
    roomId: id,
    userCount: updated.users.length,
  });
});
