// middlewares/authorizePermission.js
const authorizePermission = (permission) => {
  return (req, res, next) => {
    if (!req.user?.role?.permissions) {
      return res.status(403).json({
        success: false,
        message: "No permissions assigned",
      });
    }

    // permissions is a Map → convert to array
    const permissionsMap = req.user.role.permissions;

    // flatten all module permissions
    const allPermissions = Array.from(permissionsMap.values()).flat();

    if (!allPermissions.includes(permission) && !allPermissions.includes("*")) {
      return res.status(403).json({
        success: false,
        message: "Permission denied",
      });
    }

    next();
  };
};

module.exports = authorizePermission;
