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, restaurantId } = await req.json();

  requireUserId(userId);
  if (restaurantId == null) throw new ApiError("restaurantId is required");

  const rid = String(restaurantId);

  const updated = await atomicUpdateRoom(id, (data) => {
    if (!data.users.includes(userId)) {
      throw new ApiError("你不是该房间的成员", 403);
    }

    if (data.likes[rid]) {
      data.likes[rid] = data.likes[rid].filter((u) => u !== userId);
      if (data.likes[rid].length === 0) {
        delete data.likes[rid];
      }
    }

    if (data.match === rid) {
      data.match = null;
    }

    const count = data.swipeCounts[userId] ?? 0;
    if (count > 0) {
      data.swipeCounts[userId] = count - 1;
    }

    return data;
  });

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

  notify(id);

  return NextResponse.json({ ok: true });
});
