'use strict';

/**
 * GET /api/ticker (Session 45) — the live ticker feed.
 *
 * Returns the latest snapshot-generated events from the `ticker:items` Redis
 * list (newest first), merged with editorial pins from the TICKER_MANUAL env
 * var (a JSON array of { tag, text, color }). Public + cached 30s. Reads cache
 * only — never triggers a snapshot.
 */

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

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

const LIMIT = 30;

function parseManual() {
  const raw = process.env.TICKER_MANUAL;
  if (!raw) return [];
  try {
    const arr = JSON.parse(raw);
    return Array.isArray(arr)
      ? arr.filter((x) => x && x.text).map((x) => ({ tag: x.tag || 'ALERT', text: String(x.text), color: x.color || 'var(--text-0)' }))
      : [];
  } catch {
    return [];
  }
}

router.get('/', async (req, res) => {
  let items = [];
  try {
    const stored = await cacheGet('ticker:items');
    if (Array.isArray(stored)) items = stored;
  } catch {
    items = [];
  }
  // Snapshot events are already newest-first; editorial pins follow.
  const merged = [...items, ...parseManual()].slice(0, LIMIT);
  res.set('Cache-Control', 'public, max-age=30');
  res.json({ items: merged, count: merged.length });
});

module.exports = router;
