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

// GET /api/sessions — 获取游戏局列表（支持分页、按房间/日期/分数筛选）
router.get('/', async (req, res, next) => {
  try {
    const { roomId, page = '1', pageSize = '20', startDate, endDate, scoreMin, scoreMax } = req.query;
    const pageNum = Math.max(1, parseInt(page, 10) || 1);
    const pageSizeNum = Math.min(100, Math.max(1, parseInt(pageSize, 10) || 20));
    const skip = (pageNum - 1) * pageSizeNum;

    const where = {};
    if (roomId && String(roomId).trim()) where.roomId = String(roomId).trim();
    if (startDate || endDate) {
      where.startedAt = {};
      if (startDate) where.startedAt.gte = new Date(startDate);
      if (endDate) {
        const end = new Date(endDate);
        end.setHours(23, 59, 59, 999);
        where.startedAt.lte = end;
      }
    }
    if (scoreMin != null && scoreMin !== '') {
      const n = parseInt(scoreMin, 10);
      if (!Number.isNaN(n)) { where.score = where.score || {}; where.score.gte = n; }
    }
    if (scoreMax != null && scoreMax !== '') {
      const n = parseInt(scoreMax, 10);
      if (!Number.isNaN(n)) { where.score = where.score || {}; where.score.lte = n; }
    }

    const [total, sessions] = await Promise.all([
      prisma.gameSession.count({ where }),
      prisma.gameSession.findMany({
        where,
        orderBy: { startedAt: 'desc' },
        skip,
        take: pageSizeNum,
      }),
    ]);

    res.json({ total, page: pageNum, pageSize: pageSizeNum, data: sessions });
  } catch (err) {
    next(err);
  }
});

// GET /api/sessions/:id — 获取单局详情
router.get('/:id', async (req, res, next) => {
  try {
    const id = parseInt(req.params.id, 10);
    if (Number.isNaN(id) || id < 1) {
      return res.status(400).json({ error: '无效的游戏局 ID' });
    }
    const session = await prisma.gameSession.findUnique({
      where: { id },
    });
    if (!session) return res.status(404).json({ error: '游戏局不存在' });
    res.json(session);
  } catch (err) {
    next(err);
  }
});

module.exports = router;
