const ErrorHandler = require("../utils/ErrorHandler");

/**
 * Middleware to check if the user has the required permission.
 * Super Admins bypass this check.
 * Staff members must have the specific permission in their permissions array.
 */
const checkPermission = (requiredPermission) => {
    return (req, res, next) => {
        try {
            const user = req.user;

            if (!user) {
                return next(new ErrorHandler("Login Required", 401));
            }

            // Super Admin has all permissions
            if (user.role === 'super-admin') {
                return next();
            }

            // Check if user is staff
            if (user.role === 'staff') {
                // Check if staff has the required permission(s)
                const permissions = Array.isArray(requiredPermission) ? requiredPermission : [requiredPermission];
                const hasPermission = permissions.some(perm => user.permissions && user.permissions.includes(perm));

                if (hasPermission) {
                    return next();
                } else {
                    const permNames = permissions.map(p => p.replace('_', ' ')).join(' or ');
                    return next(new ErrorHandler(`Access Denied: You do not have permission to ${permNames}`, 403));
                }
            }

            // For other roles, allow access (access control should be handled by allowRoles)
            // This allows users/drivers/vendors to access their specific routes while enforcing permissions for staff
            return next();

        } catch (error) {
            console.error("Permission check error:", error);
            return next(new ErrorHandler("Internal Server Error during permission check", 500));
        }
    };
};

module.exports = { checkPermission };
