var resp = require('../response.js');

module.exports = (type, module) => async (req, res, next) => {
    try {
        if (!Array.isArray(req.session?.userAcl)) {
            return res.status(403).json(
                resp(
                    "Access Denied",
                    "User does not have access to this operation on this module",
                    null,
                    req,
                    false
                )
            );
        }

        for (const acl of req.session.userAcl) { 
            if (acl.name == module && acl.GroupModules[type] == true) { 
                return next();
            }
        }
        return res.status(403).json(
            resp(
                "Access Denied",
                "User does not have access to this operation on this module",
                null,
                req,
                false
            )
        );
    } 
    catch(err) {
        return res.status(500).json(
            resp(
                "Server Error",
                "Error checking ACL Access",
                null,
                req,
                false
            )
        );
    }
};