/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';
const logger = require('../../../core/logger')('contrast:async-storage:hooks');
const moduleHook = require('../../../hooks/require');
const patcher = require('../../../hooks/patcher');
const { bindFnArgAtIndex } = require('../../../core/async-storage/hooks/utils');
const { PATCH_TYPES } = require('../../../constants');

module.exports = function() {
  moduleHook.resolve({ name: 'bluebird' }, (bluebird) => {
    module.exports.patchConfig(bluebird);
    module.exports.patchAddCallbacks(bluebird);
    module.exports.patchGetNewLibraryCopy(bluebird);
  });
};

/**
 * Ensures that new library copies are also instrumented.
 * @param {function} bluebird the library export
 */
module.exports.patchGetNewLibraryCopy = function(bluebird) {
  if (typeof bluebird.getNewLibraryCopy !== 'function') {
    return;
  }

  patcher.patch(bluebird, 'getNewLibraryCopy', {
    alwaysRun: true,
    name: 'bluebird.getNewLibraryCopy',
    patchType: PATCH_TYPES.ASYNC_CONTEXT,
    post(data) {
      module.exports.patchAddCallbacks(data.result);
    }
  });
};

/**
 * This forces bluebird to use async hooks.
 * This is to ensure our AsyncStorage will
 * properly bind bluebird Promises when running
 * in a Scope(request, propagator, no instrumentation)
 *
 * http://bluebirdjs.com/docs/api/promise.config.html#async-hooks
 */
module.exports.patchConfig = function(bluebird) {
  patcher.patch(bluebird, 'config', {
    alwaysRun: true,
    name: 'bluebird.config',
    patchType: PATCH_TYPES.ASYNC_CONTEXT,
    pre(data) {
      const opts = data.args[0];
      if (opts) {
        opts.asyncHooks = true;
      }
    }
  });
};

/**
 * Even with async_hooks option set we still need to bind callbacks to our CLS
 * namespace.
 */
module.exports.patchAddCallbacks = function(bluebird) {
  if (bluebird.prototype && bluebird.prototype._addCallbacks) {
    patcher.patch(bluebird.prototype, '_addCallbacks', {
      alwaysRun: true,
      name: 'bluebird.prototype',
      patchType: PATCH_TYPES.ASYNC_CONTEXT,
      pre({ args, funcKey: identifier }) {
        // bind every function argument
        for (let idx = 0; idx < args.length; idx++) {
          bindFnArgAtIndex({ args, idx, identifier });
        }
      }
    });
  } else {
    logger.warn('skip patching bluebird.prototype._addCallbacks');
  }
};
