const { body, param, validationResult } = require('express-validator');
// Validation rules for role creation
const validateRoleCreation = [
    body('name')
        .notEmpty()
        .withMessage('Role name is required')
        .isLength({ min: 2, max: 50 })
        .withMessage('Role name must be between 2 and 50 characters')
        .matches(/^[a-zA-Z0-9_\s-]+$/)
        .withMessage('Role name can only contain letters, numbers, spaces, hyphens, and underscores'),
    body('description')
        .notEmpty()
        .withMessage('Role description is required')
        .isLength({ min: 5, max: 500 })
        .withMessage('Role description must be between 5 and 500 characters'),
    body('level')
        .isInt({ min: 1, max: 100 })
        .withMessage('Role level must be an integer between 1 and 100'),
    body('permissions')
        .optional()
        .isArray()
        .withMessage('Permissions must be an array')
        .custom((permissions) => {
        if (permissions && permissions.length > 0) {
            const invalidPermissions = permissions.filter(p => !Number.isInteger(p) || p <= 0);
            if (invalidPermissions.length > 0) {
                throw new Error('All permission IDs must be positive integers');
            }
        }
        return true;
    })
];
// Validation rules for role update
const validateRoleUpdate = [
    param('id')
        .isInt({ min: 1 })
        .withMessage('Role ID must be a positive integer'),
    body('name')
        .notEmpty()
        .withMessage('Role name is required')
        .isLength({ min: 2, max: 50 })
        .withMessage('Role name must be between 2 and 50 characters')
        .matches(/^[a-zA-Z0-9_\s-]+$/)
        .withMessage('Role name can only contain letters, numbers, spaces, hyphens, and underscores'),
    body('description')
        .notEmpty()
        .withMessage('Role description is required')
        .isLength({ min: 5, max: 500 })
        .withMessage('Role description must be between 5 and 500 characters'),
    body('level')
        .isInt({ min: 1, max: 100 })
        .withMessage('Role level must be an integer between 1 and 100'),
    body('permissions')
        .optional()
        .isArray()
        .withMessage('Permissions must be an array')
        .custom((permissions) => {
        if (permissions && permissions.length > 0) {
            const invalidPermissions = permissions.filter(p => !Number.isInteger(p) || p <= 0);
            if (invalidPermissions.length > 0) {
                throw new Error('All permission IDs must be positive integers');
            }
        }
        return true;
    })
];
// Validation rules for role ID parameter
const validateRoleId = [
    param('id')
        .isInt({ min: 1 })
        .withMessage('Role ID must be a positive integer')
];
// Validation rules for permission ID parameter
const validatePermissionId = [
    param('id')
        .isInt({ min: 1 })
        .withMessage('Permission ID must be a positive integer')
];
// Validation rules for user ID parameter
const validateUserId = [
    param('userId')
        .isInt({ min: 1 })
        .withMessage('User ID must be a positive integer')
];
// Validation rules for permission check
const validatePermissionCheck = [
    param('userId')
        .isInt({ min: 1 })
        .withMessage('User ID must be a positive integer'),
    body('permission')
        .notEmpty()
        .withMessage('Permission name is required')
        .isLength({ min: 3, max: 100 })
        .withMessage('Permission name must be between 3 and 100 characters')
        .matches(/^[a-zA-Z0-9_.-]+$/)
        .withMessage('Permission name can only contain letters, numbers, dots, hyphens, and underscores')
];
// Middleware to handle validation errors
const handleValidationErrors = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({
            status: 'error',
            message: 'Validation failed',
            errors: errors.array().map(error => ({
                field: error.path,
                message: error.msg,
                value: error.value
            }))
        });
    }
    next();
};
// Role authorization middleware
const requireRolePermission = (permission) => {
    return async (req, res, next) => {
        try {
            // Check if user has the required permission
            const Role = require('../models/Role');
            const hasPermission = await Role.userHasPermission(req.user.id, permission);
            if (!hasPermission) {
                return res.status(403).json({
                    status: 'error',
                    message: 'Insufficient permissions to perform this action'
                });
            }
            next();
        }
        catch (error) {
            next(error);
        }
    };
};
// Admin role middleware
const requireAdminRole = async (req, res, next) => {
    try {
        const Role = require('../models/Role');
        const hasAdminRole = await Role.userHasRole(req.user.id, 'Super_admin') ||
            await Role.userHasRole(req.user.id, 'Admin');
        if (!hasAdminRole) {
            return res.status(403).json({
                status: 'error',
                message: 'Admin role required to perform this action'
            });
        }
        next();
    }
    catch (error) {
        next(error);
    }
};
module.exports = {
    validateRoleCreation,
    validateRoleUpdate,
    validateRoleId,
    validatePermissionId,
    validateUserId,
    validatePermissionCheck,
    handleValidationErrors,
    requireRolePermission,
    requireAdminRole
};
//# sourceMappingURL=roleValidation.js.map