import { Router } from 'express';
import { usersController } from './users.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 profile
router.get('/me', (req, res, next) => usersController.getMe(req, res, next));

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

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

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

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

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

// Activate/Deactivate user (admin only)
router.post('/:id/activate', requireAccess({ roles: ['admin'], permission: 'users:activate' }), (req, res, next) =>
  usersController.activate(req, res, next)
);

router.post('/:id/deactivate', requireAccess({ roles: ['admin'], permission: 'users:deactivate' }), (req, res, next) =>
  usersController.deactivate(req, res, next)
);

// User roles
router.get('/:id/roles', requireAccess({ roles: ['admin'], permission: 'roles:read' }), (req, res, next) =>
  usersController.getRoles(req, res, next)
);

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

router.delete('/:id/roles/:roleId', requireAccess({ roles: ['admin'], permission: 'roles:update' }), (req, res, next) =>
  usersController.removeRole(req, res, next)
);

export default router;
