/**
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:hooks:array-prototype');
const {
  PATCH_TYPES: { MISC }
} = require('../constants');
const patcher = require('./patcher');

const getOrig = (v) => patcher.unwrap(v);

/**
 * Apply a heuristic to gauge whether we need to unwrap arguments so results
 * of SameValueZero algorithm are preserved.
 * @param {*[]} args The arguments passed to prototype method
 * @returns {boolean}
 */
function shouldUnwrap(args) {
  const [valueToFind] = args;
  return (
    typeof valueToFind === 'function' &&
    (valueToFind.name === 'Object' ||
      valueToFind.name === 'String' ||
      valueToFind.name === 'Function')
  );
}

/**
 * Checks whether we should unwrap argument and array elements before the
 * original is called.
 * @param {object} data
 */
function maybeUnwrapContext(data) {
  if (shouldUnwrap(data.args)) {
    data.args[0] = getOrig(data.args[0]);
    let i = typeof data.args[1] === 'number' ? data.args[1] : 0;
    for (i; i < data.obj.length; i++) {
      data.obj[i] = getOrig(data.obj[i]);
    }
  }
}

module.exports = function init() {
  logger.debug('patching Array includes and indexOf methods');

  patcher.patch(Array.prototype, 'includes', {
    name: 'Array',
    patchType: MISC,
    alwaysRun: true,
    pre(data) {
      maybeUnwrapContext(data);
    }
  });

  patcher.patch(Array.prototype, 'indexOf', {
    name: 'Array',
    patchType: MISC,
    alwaysRun: true,
    pre(data) {
      maybeUnwrapContext(data);
    }
  });
};
