'use strict';

/**
 * /api/lines (Session 28)
 *
 * Read-only views over the line-snapshot history (Redis). Zero credits.
 *
 *   GET /api/lines/:sport/movers                       → biggest movers today
 *   GET /api/lines/:sport/:gameId/:player/:stat        → one prop's history + classification
 */

const express = require('express');
const lineSnapshots = require('../services/lineSnapshotService');
const { createRateLimit } = require('../middleware/rateLimit');

const router = express.Router();
// Session 32 — public throttle (60/min; Redis snapshots).
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));

const MISSION_HEADER = { 'X-VYNDR-Mission': 'The market confirms the grade' };

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

router.get('/:sport/movers', async (req, res) => {
  const sport = String(req.params.sport || '').toLowerCase();
  if (!SUPPORTED.has(sport)) {
    return res.status(404).set(MISSION_HEADER).json({ error: `No line tracking for sport: ${sport}` });
  }
  const limit = req.query.limit ? Math.max(0, parseInt(req.query.limit, 10) || 0) : 20;
  try {
    const movers = await lineSnapshots.getBiggestMovers(sport, { limit });
    return res.set(MISSION_HEADER).json({ sport, movers, source: 'snapshots' });
  } catch (err) {
    console.error(`[lines/${sport}/movers]`, err.message);
    return res.set(MISSION_HEADER).json({ sport, movers: [], source: 'snapshots' });
  }
});

router.get('/:sport/:gameId/:player/:stat', async (req, res) => {
  const sport = String(req.params.sport || '').toLowerCase();
  const { gameId, player, stat } = req.params;
  try {
    const history = await lineSnapshots.getLineHistory(sport, gameId, decodeURIComponent(player), stat);
    const classification = lineSnapshots.classifyMovement(history);
    return res.set(MISSION_HEADER).json({ sport, gameId, player, stat, ...classification });
  } catch (err) {
    console.error(`[lines/${sport}/prop]`, err.message);
    return res.set(MISSION_HEADER).json({ sport, gameId, player, stat, movement: 'stable', delta: 0, snapshots: [] });
  }
});

module.exports = router;
