'use strict';

/**
 * GET /api/team/:abbr?sport=mlb (Session 51) — the Team Hub payload (roster +
 * per-player archetype/stats/props). Public, cache-backed (15 min). Returns 404
 * for an unknown MLB team; NBA/WNBA degrade to a snapshot-built roster.
 */

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

const router = express.Router();
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));

router.get('/:abbr', async (req, res) => {
  const sport = String(req.query.sport || 'mlb').toLowerCase();
  const abbr = String(req.params.abbr || '');
  try {
    const hub = await getTeamHub(sport, abbr);
    if (!hub) {
      return res.status(404).json({ error: `No ${sport.toUpperCase()} team for "${abbr}". Check the abbreviation.` });
    }
    res.set('Cache-Control', 'public, max-age=300');
    return res.json(hub);
  } catch (err) {
    console.error('[team]', err.message);
    return res.status(503).json({ error: 'Team service temporarily unavailable' });
  }
});

module.exports = router;
