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 { EVENTS_ROLES } from '../../utils/roles';
import { participantNeedsService } from './participant-needs.service';
import { upsertNeedsSchema } from './participant-needs.schemas';

const router = Router();

// GET /api/people/needs/me
router.get(
  '/me',
  authenticate,
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const needs = await participantNeedsService.findByUserId(req.user!.id);
      res.json({ needs });
    } catch (err) {
      next(err);
    }
  }
);

// PUT /api/people/needs/me
router.put(
  '/me',
  authenticate,
  validate(upsertNeedsSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const needs = await participantNeedsService.upsert(req.body, req.user!.id);
      res.json({ needs });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/people/needs/aggregate
router.get(
  '/aggregate',
  authenticate,
  requireRole(...EVENTS_ROLES),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const userIdsParam = req.query.userIds as string | undefined;
      const contactIdsParam = req.query.contactIds as string | undefined;
      const userIds = userIdsParam ? userIdsParam.split(',').filter(Boolean) : [];
      const contactIds = contactIdsParam ? contactIdsParam.split(',').filter(Boolean) : [];
      const summary = await participantNeedsService.aggregateForVoters(userIds, contactIds);
      res.json({ summary });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/people/needs/user/:userId
router.get(
  '/user/:userId',
  authenticate,
  requireRole(...EVENTS_ROLES),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const userId = req.params.userId as string;
      const needs = await participantNeedsService.findByUserId(userId);
      res.json({ needs });
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/people/needs/contact/:contactId
router.get(
  '/contact/:contactId',
  authenticate,
  requireRole(...EVENTS_ROLES),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const contactId = req.params.contactId as string;
      const needs = await participantNeedsService.findByContactId(contactId);
      res.json({ needs });
    } catch (err) {
      next(err);
    }
  }
);

// DELETE /api/people/needs/:id
router.delete(
  '/:id',
  authenticate,
  requireRole(...EVENTS_ROLES),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      await participantNeedsService.deleteById(id);
      res.status(204).send();
    } catch (err) {
      next(err);
    }
  }
);

export { router as participantNeedsRouter };
