import { Router } from 'express';
import { rolesController } from './roles.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);

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

// Get system roles (admin)
router.get('/system', requireAccess({ roles: ['admin'], permission: 'roles:read' }), (req, res, next) =>
  rolesController.getSystemRoles(req, res, next)
);

// Get role by ID (admin, manager)
router.get('/:id', requireAccess({ roles: ['admin', 'manager'], permission: 'roles:read' }), (req, res, next) =>
  rolesController.findById(req, res, next)
);

// Create role (admin only)
router.post('/', requireAccess({ roles: ['admin'], permission: 'roles:create' }), (req, res, next) =>
  rolesController.create(req, res, next)
);

// Update role (admin only)
router.put('/:id', requireAccess({ roles: ['admin'], permission: 'roles:update' }), (req, res, next) =>
  rolesController.update(req, res, next)
);

// Delete role (admin only)
router.delete('/:id', requireAccess({ roles: ['admin'], permission: 'roles:delete' }), (req, res, next) =>
  rolesController.delete(req, res, next)
);

// Role permissions management
router.get('/:id/permissions', requireAccess({ roles: ['admin', 'manager'], permission: 'permissions:read' }), (req, res, next) =>
  rolesController.getPermissions(req, res, next)
);

router.put('/:id/permissions', requireAccess({ roles: ['admin'], permission: 'permissions:update' }), (req, res, next) =>
  rolesController.assignPermissions(req, res, next)
);

router.post('/:id/permissions', requireAccess({ roles: ['admin'], permission: 'permissions:update' }), (req, res, next) =>
  rolesController.addPermission(req, res, next)
);

router.delete('/:id/permissions/:permissionId', requireAccess({ roles: ['admin'], permission: 'permissions:update' }), (req, res, next) =>
  rolesController.removePermission(req, res, next)
);

export default router;
