import { Router, Request, Response, NextFunction } from 'express';
import { campaignsService } from './campaigns.service';
import { listModerationQueueSchema, moderateCampaignSchema } from './campaigns.schemas';
import { validate } from '../../../middleware/validate';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { INFLUENCE_ROLES } from '../../../utils/roles';
import { eventBus } from '../../../services/event-bus.service';

const router = Router();

router.use(authenticate);
router.use(requireRole(...INFLUENCE_ROLES));

// GET /api/campaigns/moderation/queue — list moderation queue
router.get(
  '/moderation/queue',
  validate(listModerationQueueSchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await campaignsService.findModerationQueue(req.query as any, req.user!);
      res.json(result);
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/campaigns/moderation/stats — moderation stats
router.get(
  '/moderation/stats',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const stats = await campaignsService.getModerationStats();
      res.json(stats);
    } catch (err) {
      next(err);
    }
  }
);

// PATCH /api/campaigns/moderation/:id — moderate a campaign
router.patch(
  '/moderation/:id',
  validate(moderateCampaignSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const before = await campaignsService.findById(id, req.user!);
      const campaign = await campaignsService.moderateCampaign(id, req.body, req.user!);
      eventBus.publish('campaign.status.changed', {
        campaignId: campaign.id,
        title: campaign.title,
        slug: campaign.slug,
        oldStatus: before.moderationStatus ?? 'PENDING',
        newStatus: campaign.moderationStatus ?? 'PENDING',
      });
      if (campaign.status === 'ACTIVE' && before.status !== 'ACTIVE') {
        eventBus.publish('campaign.published', {
          campaignId: campaign.id,
          title: campaign.title,
          slug: campaign.slug,
        });
      }
      res.json(campaign);
    } catch (err) {
      next(err);
    }
  }
);

export { router as campaignModerationRouter };
