import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../../middleware/auth.middleware';
import { requireRole } from '../../../middleware/rbac.middleware';
import { validate } from '../../../middleware/validate';
import { exportContactsPreviewSchema, exportContactsSchema } from './canvass-export.schemas';
import {
  previewExportContacts,
  exportContactsToCampaign,
  getCutCampaignAnalytics,
} from './canvass-export.service';
import { MAP_ROLES } from '../../../utils/roles';

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

// POST /api/map/canvass/export-contacts/preview — preview matching contacts
router.post(
  '/export-contacts/preview',
  validate(exportContactsPreviewSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await previewExportContacts(req.body);
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

// POST /api/map/canvass/export-contacts — export contacts to campaign
router.post(
  '/export-contacts',
  validate(exportContactsSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await exportContactsToCampaign(req.body);
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/map/canvass/analytics/cuts — per-cut campaign analytics
router.get(
  '/analytics/cuts',
  async (_req: Request, res: Response, next: NextFunction) => {
    try {
      const analytics = await getCutCampaignAnalytics();
      res.json({ cuts: analytics });
    } catch (err) {
      next(err);
    }
  },
);

export { router as canvassExportRouter };
