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

// GET /api/stats/overview — 总览统计（总局数、总房间数、平均分、今日局数、当前进行中房间数）
router.get('/overview', async (_req, res, next) => {
  try {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const [totalSessions, todaySessions, avgScoreResult, activeRooms, totalRooms] = await Promise.all([
      prisma.gameSession.count(),
      prisma.gameSession.count({ where: { startedAt: { gte: today } } }),
      prisma.gameSession.aggregate({
        _avg: { score: true },
        where: { status: 'finished' },
      }),
      prisma.room.count({ where: { status: 'playing' } }),
      prisma.room.count(),
    ]);

    res.json({
      totalSessions,
      todaySessions,
      totalRooms,
      avgScore: Math.round(avgScoreResult._avg.score ?? 0),
      activeRooms,
    });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
