const express = require('express');
const db = require('../database');

const router = express.Router();

// Get overall statistics
router.get('/', (req, res) => {
  try {
    const stats = {
      games: db.prepare('SELECT COUNT(*) as count FROM games').get(),
      gamesEnabled: db.prepare('SELECT COUNT(*) as count FROM games WHERE enabled = 1').get(),
      packs: db.prepare('SELECT COUNT(DISTINCT pack_name) as count FROM games').get(),
      sessions: db.prepare('SELECT COUNT(*) as count FROM sessions').get(),
      activeSessions: db.prepare('SELECT COUNT(*) as count FROM sessions WHERE is_active = 1').get(),
      totalGamesPlayed: db.prepare('SELECT COUNT(*) as count FROM session_games').get(),
      mostPlayedGames: db.prepare(`
        SELECT g.id, g.title, g.pack_name, g.play_count, g.popularity_score, g.upvotes, g.downvotes
        FROM games g
        WHERE g.play_count > 0
        ORDER BY g.play_count DESC
        LIMIT 10
      `).all(),
      topRatedGames: db.prepare(`
        SELECT g.id, g.title, g.pack_name, g.play_count, g.popularity_score, g.upvotes, g.downvotes
        FROM games g
        WHERE g.popularity_score > 0
        ORDER BY g.popularity_score DESC
        LIMIT 10
      `).all()
    };

    res.json(stats);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

