import { Router, type IRouter } from 'express';
import { authenticate, authorize } from '../middlewares/auth.middleware.js';
import { tenantMiddleware } from '../middlewares/tenant.middleware.js';
import * as ctrl from '../controllers/cartera.controller.js';
import * as asignacionesCtrl from '../controllers/asignaciones.controller.js';

const router: IRouter = Router();

router.use(authenticate);
router.use(tenantMiddleware);

// Static routes first
router.get('/supervisores', authorize('owner', 'supervisor'), ctrl.getSupervisores);

// Asignaciones de obligaciones/tareas a auxiliares (antes de /:id para evitar match dinámico)
router.get('/asignaciones', authorize('owner', 'supervisor'), asignacionesCtrl.listPorSupervisor);
router.get('/asignaciones/mias', authorize('auxiliar'), asignacionesCtrl.listPorAuxiliar);
router.get('/asignaciones/sin-asignar', authorize('owner', 'supervisor'), asignacionesCtrl.listSinAsignar);
router.get('/asignaciones/auxiliares-elegibles/:contribuyenteId', authorize('owner', 'supervisor'), asignacionesCtrl.listAuxiliaresElegibles);

// Read: owner + supervisor + auxiliar
router.get('/', authorize('owner', 'supervisor', 'auxiliar'), ctrl.list);
router.get('/:id', authorize('owner', 'supervisor', 'auxiliar'), ctrl.getById);
router.get('/:id/subcarteras', authorize('owner', 'supervisor', 'auxiliar'), ctrl.listSubcarteras);
router.get('/:id/entidades', authorize('owner', 'supervisor', 'auxiliar'), ctrl.getEntidades);
router.get('/:id/auxiliares', authorize('owner', 'supervisor', 'auxiliar'), ctrl.getAuxiliares);
router.get('/:supervisorId/auxiliares-disponibles', authorize('owner', 'supervisor'), ctrl.getAuxiliaresDelSupervisor);

// Write: owner + supervisor (with permission checks in controller)
router.post('/', authorize('owner', 'supervisor'), ctrl.create);
router.put('/:id', authorize('owner', 'supervisor'), ctrl.update);
router.delete('/:id', authorize('owner', 'supervisor'), ctrl.remove);
router.post('/:id/subcarteras', authorize('owner', 'supervisor'), ctrl.createSubcartera);
router.post('/:id/entidades', authorize('owner', 'supervisor'), ctrl.addEntidad);
router.delete('/:id/entidades/:entidadId', authorize('owner', 'supervisor'), ctrl.removeEntidad);
router.post('/:id/auxiliares', authorize('owner', 'supervisor'), ctrl.addAuxiliar);
router.delete('/:id/auxiliares/:auxiliarUserId', authorize('owner', 'supervisor'), ctrl.removeAuxiliar);

export default router;
