/**
 * /api/hotlist/:sport (Session 23)
 *
 * Rolling recent-window leaders, ranked by how far ABOVE baseline each
 * player is trending. NO API calls — reads warm cached game logs and runs
 * the pure hot-list engine. Supports `?stat=points` and `?limit=N`.
 *
 * Response: { sport, stat, players: [...], source: 'computed' }
 */

const express = require('express');
const hotListService = require('../services/hotListService');
const { loadRosterLogs } = require('../services/rosterLogs');
const { createRateLimit } = require('../middleware/rateLimit');

const router = express.Router();
// Session 32 — public throttle (60/min; pure engine over cached logs).
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));

const MISSION_HEADER = { 'X-VYNDR-Mission': 'Hot right now' };

const SUPPORTED = new Set(['nba', 'wnba', 'mlb', 'soccer']);

router.get('/:sport', async (req, res) => {
  const sport = String(req.params.sport || '').toLowerCase();
  if (!SUPPORTED.has(sport)) {
    return res.status(404).set(MISSION_HEADER).json({ error: `No hot list for sport: ${sport}` });
  }
  const stat = req.query.stat ? String(req.query.stat).toLowerCase() : 'all';
  const limit = req.query.limit ? Math.max(0, parseInt(req.query.limit, 10) || 0) : 0;

  try {
    const roster = await loadRosterLogs(sport);
    const players = hotListService.computeHotList(roster, sport, { stat, limit });
    return res.set(MISSION_HEADER).json({ sport, stat, players, source: 'computed' });
  } catch (err) {
    console.error(`[hotlist/${sport}]`, err.message);
    return res.set(MISSION_HEADER).json({ sport, stat, players: [], source: 'computed' });
  }
});

module.exports = router;
