const express = require('express');
const { sendToScreen, joinRoom, leaveAllRooms, screenSockets } = require('../socket');
const { getRoomTimerSnapshot } = require('../socket/roomHandler');

const router = express.Router();
const prisma = require('../prisma/client');

// GET /api/screens — 获取所有大屏及其当前绑定状态（含在线状态）
router.get('/', async (_req, res, next) => {
  try {
    const screens = await prisma.screenConfig.findMany({
      orderBy: { createdAt: 'desc' },
    });
    const list = screens.map((s) => ({
      ...s,
      online: screenSockets.has(s.screenName) &&
              screenSockets.get(s.screenName).readyState === 1, // OPEN = 1
    }));
    res.json(list);
  } catch (err) {
    next(err);
  }
});

// POST /api/screens/:screenId/bindRoom — 绑定大屏到指定房间
// body: { roomId: string | null }
router.post('/:screenId/bindRoom', async (req, res, next) => {
  try {
    const { screenId } = req.params;
    const { roomId } = req.body;

    const screen = await prisma.screenConfig.update({
      where: { screenName: screenId },
      data: { currentRoomId: roomId || null },
    });

    // 实时通知大屏切换房间
    const targetWs = screenSockets.get(screenId);
    if (targetWs && targetWs.readyState === 1) {
      // 退订旧房间，订阅新房间
      leaveAllRooms(targetWs);
      if (roomId) joinRoom(targetWs, roomId);
      // 通知大屏
      targetWs.sendEvent('screen:roomChanged', { roomId: roomId || null });
      const timerSnapshot = getRoomTimerSnapshot(roomId);
      if (timerSnapshot) {
        targetWs.sendEvent('room:gameStart', {
          roomId: timerSnapshot.roomId,
          gameDuration: timerSnapshot.durationSec,
          startAtMs: timerSnapshot.startAtMs,
        });
      }
    }

    res.json(screen);
  } catch (err) {
    if (err.code === 'P2025') {
      return res.status(404).json({ error: '大屏不存在' });
    }
    next(err);
  }
});

module.exports = router;
