import { Router, Request, Response, NextFunction } from 'express';
import { strawPollsService } from './polls.service';
import { redis } from '../../config/redis';

const widgetRouter = Router();

// Lightweight JSON for MkDocs widget embeds (cached 60s)
widgetRouter.get('/widget/:slug', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const slug = req.params.slug as string;
    const cacheKey = `straw-poll-widget:${slug}`;

    // Check Redis cache
    const cached = await redis.get(cacheKey);
    if (cached) {
      res.set('X-Cache', 'HIT');
      return res.json(JSON.parse(cached));
    }

    const poll = await strawPollsService.findBySlugWidget(slug);
    if (!poll) return res.status(404).json({ error: 'Poll not found' });

    // Cache for 60 seconds
    await redis.set(cacheKey, JSON.stringify(poll), 'EX', 60);
    res.set('X-Cache', 'MISS');
    res.json(poll);
  } catch (err) { next(err); }
});

export { widgetRouter as strawPollWidgetRouter };
