const express = require('express');
const router = express.Router();
const prisma = require('../prisma/client');
const { getWaitingRoomTeamInfo } = require('../socket/roomHandler');
const { getActiveRoomSubscriberCount } = require('../socket');

// GET /api/rooms — 获取所有房间列表（进行中房间含当前分数）
router.get('/', async (_req, res, next) => {
  try {
    const rooms = await prisma.room.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        sessions: {
          where: { status: 'playing' },
          take: 1,
        },
      },
    });
    res.json(
      rooms.map(({ sessions, ...r }) => ({
        ...r,
        currentScore: sessions[0]?.score ?? 0,
      }))
    );
  } catch (err) {
    next(err);
  }
});

// GET /api/rooms/:roomId — 获取指定房间详情（含游戏局列表）
router.get('/:roomId', async (req, res, next) => {
  try {
    const room = await prisma.room.findUnique({
      where: { roomId: req.params.roomId },
      include: {
        sessions: {
          orderBy: { startedAt: 'desc' },
        },
      },
    });
    if (!room) return res.status(404).json({ error: '房间不存在' });
    res.json(room);
  } catch (err) {
    next(err);
  }
});

// GET /api/rooms/:roomId/check — 校验房间是否存在且处于等待中
// 返回：{ ok: bool, roomId, totalSeats, perTeamSeats, teamA, teamB, message? }
//   teamA / teamB: 当前各队人数；perTeamSeats: 每队座位上限（totalSeats / 2）
router.get('/:roomId/check', async (req, res, next) => {
  try {
    const { roomId } = req.params;
    const room = await prisma.room.findUnique({
      where: { roomId },
      select: { status: true, totalSeats: true },
    });

    if (!room) {
      return res.json({ ok: false, message: '房间不存在' });
    }
    if (room.status !== 'waiting') {
      return res.json({ ok: false, message: room.status === 'playing' ? '房间已开始游戏' : '房间已结束' });
    }

    // 从内存等待表中获取实时队伍人数
    const teamInfo = getWaitingRoomTeamInfo(roomId);
    const perTeamSeats = teamInfo?.perTeamSeats ?? Math.floor(room.totalSeats / 2);
    const teamA = teamInfo?.teamA ?? 0;
    const teamB = teamInfo?.teamB ?? 0;

    res.json({ ok: true, roomId, totalSeats: room.totalSeats, perTeamSeats, teamA, teamB });
  } catch (err) {
    next(err);
  }
});

// POST /api/rooms/allocate — 分配下一个递增的唯一房间号（从 001 开始，无上限）
// 返回：{ roomId: string }
router.post('/allocate', async (_req, res, next) => {
  try {
    const roomId = await allocateRoomId();
    if (!roomId) {
      return res.status(503).json({ error: '当前房间已满，请稍后再试' });
    }
    res.json({ roomId });
  } catch (err) {
    next(err);
  }
});

/**
 * 分配房间号：
 * 1. 优先复用已结束（finished）的最小房间号
 * 2. 复用前要求该房间当前没有任何活跃订阅连接
 * 3. 没有可复用的，则取最大房间号 +1 递增
 * 4. 从 1 开始，无上限
 * @returns {Promise<string>} 房间号字符串
 */
async function allocateRoomId() {
  // 优先找一个已结束且当前无人订阅的房间号复用（取最小的）
  const finishedRooms = await prisma.room.findMany({
    where: { status: 'finished' },
    orderBy: { roomId: 'asc' },
    select: { roomId: true },
  });

  for (const room of finishedRooms) {
    if (getActiveRoomSubscriberCount(room.roomId) === 0) {
      return room.roomId;
    }
  }

  // 没有可复用的，取最大房间号 +1
  const last = await prisma.room.findFirst({
    orderBy: { roomId: 'desc' },
    select: { roomId: true },
  });

  const lastNum = last ? parseInt(last.roomId, 10) : 0;
  return String(lastNum + 1);
}

module.exports = router;
