/**
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 path = require('path');
const policyUtil = require('../policy/util');
const { PATCH_TYPES } = require('../../constants');

const {
  SCOPE_NAMES: { NO_INSTRUMENTATION }
} = require('../../core/async-storage/scopes');

module.exports = class Deadzones {
  constructor(agent, deadzones) {
    this.deadzones = deadzones;
    // load unsafe deadzones from user config.
    const cfg = agent.config;
    ((cfg.agent && cfg.agent.node.unsafe.deadzones) || []).forEach(
      (deadzone) => {
        // this will take precedence over hardcoded deadzones.
        this.deadzones[deadzone] = { enabled: true };
      }
    );

    Object.keys(this.deadzones).forEach((key) => {
      const deadzone = this.deadzones[key];
      if (!policyUtil.isEnabled(deadzone)) return;

      policyUtil.createPatch(key, deadzone, {
        // We don't need a pre or post here because there's no reason
        // to register a listener for this; the rewritten function will
        // convert types on its own
        name: key,
        patchType: PATCH_TYPES.DEADZONE,
        scope: NO_INSTRUMENTATION,
        alwaysRun: true
      });
    });
  }

  /**
   * @param {string} filename
   * @return {boolean}
   */
  isDeadzonedModule(filename) {
    for (const [key, value] of Object.entries(this.deadzones)) {
      if (
        filename.indexOf(path.join('node_modules', key)) > -1 &&
        policyUtil.isEnabled(value)
      ) {
        return true;
      }
    }
    return false;
  }

  /**
   * @param {string} name
   * @return {boolean}
   */
  isDeadzoned(name) {
    for (const [key, value] of Object.entries(this.deadzones)) {
      if (
        (name == key || name === value.moduleName) &&
        policyUtil.isEnabled(value)
      ) {
        return true;
      }
    }
    return false;
  }

  /**
   * @param {string} moduleName
   * @return {string[]}
   */
  getDeadzonedMethods(moduleName) {
    const deadzonedModule = this.deadzones[moduleName];
    return deadzonedModule ? deadzonedModule.methods : [];
  }
};
