/**
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('../logger')('contrast:rewrite:injections');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const Membrane = require('../../assess/membrane');
const { toUntrackedString } = require('../../assess/utils');

class Injection {
  /**
   * @param {string|void} name
   * @param {string} id
   * @param {any} value
   */
  constructor(name, id, value) {
    this.name = name;
    this.id = id;
    this.value = value;

    this._enabled = false;

    Object.defineProperty(global, id, {
      value,
      enumerable: false
    });
  }

  enabled() {
    return this._enabled;
  }

  enable() {
    logger.trace(`enabling ${this.id} injection`);
    this._enabled = true;
  }
}

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

const ContrastMethods = new Injection(null, 'ContrastMethods', {
  __add: function __add(left, right) {
    const ret = getOrig(left) + getOrig(right);
    return ret;
  },
  __forceCopy: function __forceCopy(handle) {
    // Used to force a copy of handle:
    // https://stackoverflow.com/a/31733628
    // This is a workaround for CONTRAST-30333, in which something we
    // suspect is a v8 bug means that handle will otherwise be clobbered
    // and if it was externalized, we will lose the data associated with it
    if (typeof handle === 'string') {
      handle = toUntrackedString(handle);
    }
    return handle;
  },
  __cast: function __cast(val) {
    return getOrig(val);
  },
  __doubleEqual: function __doubleEqual(left, right) {
    left = getOrig(left);
    right = getOrig(right);

    return left == right;
  },
  __notDoubleEqual: function __notDoubleEqual(left, right) {
    left = getOrig(left);
    right = getOrig(right);

    return left != right;
  },
  __tripleEqual: function __tripleEqual(left, right) {
    left = getOrig(left);
    right = getOrig(right);

    return left === right;
  },
  __notTripleEqual: function __notDoubleEqual(left, right) {
    left = getOrig(left);
    right = getOrig(right);

    return left !== right;
  },
  __contrastTag: function __contrastTag(strings) {
    // XXX implemented in lib/assess/propagators/templates.js
  },
  __contrastEval: function __contrastEval(str) {
    return str;
  },
  // TODO: NODE-2020
  __importDefault(mod, source, url) {},
  __importNamespace(mod, source, url) {},
  __import(mod, spec, source, url) {}
});

ContrastMethods.enable();

const injections = {
  ContrastMethods,
  JSON: new Injection('JSON', 'ContrastJSON', Object.create(JSON)),
  Function: new Injection(
    'Function',
    'ContrastFunction',
    patcher.patch(global.Function, {
      name: 'Function.value',
      patchType: PATCH_TYPES.INJECTION
    })
  ),
  Object: new Injection(
    'Object',
    'ContrastObject',
    patcher.patch(global.Object, {
      name: 'Object',
      patchType: PATCH_TYPES.INJECTION
    })
  ),
  String: new Injection(
    'String',
    'ContrastString',
    patcher.patch(global.String, {
      name: 'String',
      patchType: PATCH_TYPES.INJECTION
    })
  ),
  Number: new Injection(
    'Number',
    'ContrastNumber',
    patcher.patch(global.Number, {
      name: 'Number',
      patchType: PATCH_TYPES.INJECTION
    })
  )
};

module.exports = {
  /**
   * Allows access to injections by name.
   * @param {string} name
   * @returns {Injection}
   */
  get(name) {
    return injections[name];
  },

  /**
   * Returns enabled injections.
   * @returns {Injection[]}
   */
  getEnabled() {
    return Object.values(injections).reduce(
      (enabled, injection) =>
        injection.enabled() ? [...enabled, injection] : enabled,
      []
    );
  }
};
