import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { emailQueueService } from '../../../services/email-queue.service';
import { INFLUENCE_ROLES } from '../../../utils/roles';

const router = Router();
router.use(authenticate);
router.use(requireRole(...INFLUENCE_ROLES));

// GET /api/email-queue/stats
router.get(
  '/stats',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const stats = await emailQueueService.getStats();
      res.json(stats);
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/email-queue/pause
router.post(
  '/pause',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      await emailQueueService.pause();
      res.json({ message: 'Queue paused' });
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/email-queue/resume
router.post(
  '/resume',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      await emailQueueService.resume();
      res.json({ message: 'Queue resumed' });
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/email-queue/clean
router.post(
  '/clean',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const cleaned = await emailQueueService.clean();
      res.json({ message: `Cleaned ${cleaned} completed jobs`, cleaned });
    } catch (err) {
      next(err);
    }
  }
);

export { router as emailQueueRouter };
