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 body = await req.json().catch(() => ({}));
  const userId = body?.userId;
  requireUserId(userId);

  let restaurantIds: string[] | undefined;
  if (body?.restaurantIds && Array.isArray(body.restaurantIds)) {
    restaurantIds = body.restaurantIds;
  }

  const updated = await atomicUpdateRoom(id, (data) => {
    if (!data.users.includes(userId) && data.creatorId !== userId) {
      throw new ApiError("只有房间成员可以重置", 403);
    }

    if (restaurantIds && restaurantIds.length > 0) {
      const idSet = new Set(restaurantIds);
      data.restaurants = data.restaurants.filter((r) => idSet.has(r.id));
    }
    data.likes = {};
    data.swipeCounts = {};
    data.match = null;
    return data;
  });

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

  notify(id);

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