/**
 * /api/news/:sport (Wave 2A) — the FREE ESPN news wire. NO odds-api credits.
 *
 * Response contract:
 *   { sport, items: [{ id, headline, description, published (ISO), type,
 *                      athlete?: { name, key }, team?: string, href }] }
 * Newest first, cap ~25. Empty feed / unknown sport → { sport, items: [] }.
 * Never errors.
 */

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

const router = express.Router();
// Public throttle (60/min; ESPN is free but be respectful).
router.use(createRateLimit({ windowMs: 60_000, max: 60 }));

const MISSION_HEADER = { 'X-VYNDR-Mission': 'The slate is never empty' };

router.get('/:sport', async (req, res) => {
  const sport = String(req.params.sport || '').toLowerCase();
  try {
    const { getNews } = require('../services/newsService');
    const payload = await getNews(sport);
    res.set('Cache-Control', 'public, max-age=600');
    return res.set(MISSION_HEADER).json(payload);
  } catch (err) {
    console.error('[news]', err.message);
    return res.set(MISSION_HEADER).json({ sport, items: [] });
  }
});

module.exports = router;
