import { Router } from 'express';
import { permissionsController } from './permissions.controller.js';
import { authenticate } from '../../shared/middleware/auth.middleware.js';
import { requireAccess } from '../../shared/middleware/rbac.middleware.js';

const router = Router();

// All routes require authentication
router.use(authenticate);

// Get current user's permissions (any authenticated user)
router.get('/me', (req, res, next) =>
  permissionsController.getMyPermissions(req, res, next)
);

// Check permissions for current user (any authenticated user)
router.post('/check', (req, res, next) =>
  permissionsController.checkPermissions(req, res, next)
);

// List all permissions (admin, manager)
router.get('/', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.findAll(req, res, next)
);

// Get available modules (admin, manager)
router.get('/modules', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.getModules(req, res, next)
);

// Get available resources (admin, manager)
router.get('/resources', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.getResources(req, res, next)
);

// Get permissions grouped by module (admin, manager)
router.get('/grouped', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.getGrouped(req, res, next)
);

// Get permissions by module (admin, manager)
router.get('/by-module/:module', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.getByModule(req, res, next)
);

// Get permission matrix for admin UI (admin only)
router.get('/matrix', requireAccess({ roles: ['admin'], permission: 'permissions:read' }), (req, res, next) =>
  permissionsController.getMatrix(req, res, next)
);

// Get effective permissions for a specific user (admin only)
router.get('/user/:userId', requireAccess({ roles: ['admin'], permission: 'users:read' }), (req, res, next) =>
  permissionsController.getUserPermissions(req, res, next)
);

export default router;
