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 { effectivenessService } from './effectiveness.service';
import {
  effectivenessQuerySchema,
  trendQuerySchema,
  geoQuerySchema,
  repQuerySchema,
} from './effectiveness.schemas';
import { INFLUENCE_ROLES } from '../../../utils/roles';

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

// GET /api/influence/effectiveness/overview
router.get(
  '/overview',
  validate(effectivenessQuerySchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = await effectivenessService.getOverviewStats(req.query as any);
      res.json(data);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/influence/effectiveness/representatives
router.get(
  '/representatives',
  validate(repQuerySchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = await effectivenessService.getRepresentativeEffectiveness(req.query as any);
      res.json(data);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/influence/effectiveness/geographic
router.get(
  '/geographic',
  validate(geoQuerySchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = await effectivenessService.getGeographicBreakdown(req.query as any);
      res.json(data);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/influence/effectiveness/funnel
router.get(
  '/funnel',
  validate(effectivenessQuerySchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = await effectivenessService.getFunnelData(req.query as any);
      res.json(data);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/influence/effectiveness/trends
router.get(
  '/trends',
  validate(trendQuerySchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = await effectivenessService.getActivityTrends(req.query as any);
      res.json(data);
    } catch (err) {
      next(err);
    }
  },
);

export { router as effectivenessRouter };
