'use strict';

/**
 * /api/books (Session 28)
 *
 * Book comparison views over the CACHED odds props — zero odds-api
 * credits (it never triggers a fetch; it reads what's already cached).
 *
 *   GET /api/books/:sport                 → best lines tonight (sorted by savings)
 *   GET /api/books/:sport/:player/:stat   → book-by-book for one prop
 *
 * `?side=over|under` selects which side to optimize (default over).
 */

const express = require('express');
const bookComparison = require('../services/bookComparisonService');
const { cacheGet } = require('../utils/redis');
const { createRateLimit } = require('../middleware/rateLimit');

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

const MISSION_HEADER = { 'X-VYNDR-Mission': 'Never leave money on the table' };

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

// Read cached grouped props for a sport without triggering a fetch.
// oddsService caches `odds:{sport}:{utcDate}` = { updated_at, props, spreads }.
async function readCachedProps(sport) {
  const utcDate = new Date().toISOString().split('T')[0];
  const cache =
    (await cacheGet(`odds:${sport}:${utcDate}`)) ??
    (await cacheGet(`odds:${sport}`));
  if (!cache) return [];
  return Array.isArray(cache.props) ? cache.props : [];
}

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 book comparison for sport: ${sport}` });
  }
  const side = req.query.side === 'under' ? 'under' : 'over';
  const limit = req.query.limit ? Math.max(0, parseInt(req.query.limit, 10) || 0) : 20;
  try {
    const props = await readCachedProps(sport);
    const lines = bookComparison.bestLines(props, { side, limit });
    return res.set(MISSION_HEADER).json({ sport, side, bestLines: lines, source: 'odds-cache' });
  } catch (err) {
    console.error(`[books/${sport}]`, err.message);
    return res.set(MISSION_HEADER).json({ sport, side, bestLines: [], source: 'odds-cache' });
  }
});

router.get('/:sport/:player/:stat', async (req, res) => {
  const sport = String(req.params.sport || '').toLowerCase();
  const player = decodeURIComponent(req.params.player);
  const stat = req.params.stat;
  const side = req.query.side === 'under' ? 'under' : 'over';
  try {
    const props = await readCachedProps(sport);
    const prop = props.find(
      (p) => (p.player || '').toLowerCase() === player.toLowerCase() &&
        (p.stat_type || p.stat || '').toLowerCase() === stat.toLowerCase(),
    );
    if (!prop) {
      return res.status(404).set(MISSION_HEADER).json({ error: 'Prop not found in current slate.' });
    }
    const comparison = bookComparison.compareProp(prop, side);
    if (!comparison) {
      return res.set(MISSION_HEADER).json({ sport, player, stat, side, books: [], bestBook: null });
    }
    return res.set(MISSION_HEADER).json({ sport, ...comparison });
  } catch (err) {
    console.error(`[books/${sport}/prop]`, err.message);
    return res.status(500).set(MISSION_HEADER).json({ error: 'Comparison failed' });
  }
});

module.exports = router;
