import { Router, Request, Response, NextFunction } from 'express';
import { homepageService } from './homepage.service';
import { homepageStats } from '../../services/event-listeners/homepage-stats.listener';

const router = Router();

// GET /api/homepage — Aggregated public homepage data (no auth)
router.get('/', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const data = await homepageService.getPublicData();
    res.json(data);
  } catch (err) {
    next(err);
  }
});

// GET /api/homepage/live-stats — Real-time EventBus-driven counters (no auth)
router.get('/live-stats', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const counters = await homepageStats.getCounters();
    const recentSignups = await homepageStats.getRecent('signups', 5);
    const recentDonations = await homepageStats.getRecent('donations', 5);
    const recentResponses = await homepageStats.getRecent('responses', 5);
    res.json({ counters, recent: { signups: recentSignups, donations: recentDonations, responses: recentResponses } });
  } catch (err) {
    next(err);
  }
});

export { router as homepageRouter };
