/**
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:hooks');
const { ASYNC_CONTEXT } = require('../../../constants').PATCH_TYPES;
const requireHook = require('../../../hooks/require');
const resolveCallbackIdx = require('../../../util/callback-resolver');
const patcher = require('../../../hooks/patcher');
const utils = require('./utils');
const semver = require('semver');

/**
 * Hooks a method to properly bind to AsyncStorage
 * @param {Object} prototype to hook
 * @param {String} method to hook
 * @param {String} patchName of the patch
 */
function hookMethod(obj, method, patchName) {
  patcher.patch(obj, method, {
    name: patchName,
    patchType: ASYNC_CONTEXT,
    alwaysRun: true,
    pre: (data) => {
      const { args, funcKey: identifier } = data;
      const idx = resolveCallbackIdx(data.args);

      if (idx >= 0) {
        utils.bindFnArgAtIndex({ args, idx, identifier });
      }
    },
  });
}

/**
 * Registers the hooks for mongodb and mongodb-core
 */
function init() {
  logger.info('applying non-policy hook: mongodb');

  requireHook.resolve(
    { name: 'mongodb-core', file: 'lib/topologies/server.js' },
    (server) => {
      const methods = ['command', 'insert', 'update', 'remove', 'logout'];
      for (const method of methods) {
        const name = `mongodb-core.${server.prototype.constructor.name}.prototype`;
        hookMethod(server.prototype, method, name);
      }
    }
  );

  requireHook.resolve(
    { name: 'mongodb-core', file: 'lib/cursor.js' },
    (cursor) => {
      const name = `mongodb-core.${cursor.prototype.constructor.name}.prototype`;
      hookMethod(cursor.prototype, 'next', name);
    }
  );

  requireHook.resolve(
    {
      name: 'mongodb',
      file: 'lib/topologies/topology_base.js',
      version: '>=3.3.0',
    },
    (tpl, { version }) => {
      if (semver.lt(version, '4.0.0')) {
        return patcher.patch(tpl, 'TopologyBase', {
          name: 'mongodb.TopologyBase',
          patchType: ASYNC_CONTEXT,
          alwaysRun: true,
          post: (data) => {
            const methods = ['command', 'insert', 'update', 'remove'];
            for (const method of methods) {
              hookMethod(data.result, method, 'mongodb.TopologyBase');
            }
          },
        });
      }
    }
  );

  requireHook.resolve(
    {
      name: 'mongodb',
      file: 'lib/topologies/native_topology.js',
      version: '>=3.3.0',
    },
    (tpl, { version }) => {
      if (semver.lt(version, '4.0.0')) {
        return patcher.patch(tpl, {
          name: 'mongodb.NativeTopology',
          patchType: ASYNC_CONTEXT,
          alwaysRun: true,
          post: (data) => {
            const methods = ['command', 'insert', 'update', 'remove'];
            for (const method of methods) {
              hookMethod(data.result, method, 'mongodb.NativeTopology');
            }
          },
        });
      }
    }
  );

  requireHook.resolve(
    {
      name: 'mongodb',
      file: 'lib/operations/command.js',
      version: '>=3.3.0',
    },
    (command, { version }) => {
      if (semver.gte(version, '4.0.0')) {
        return patcher.patch(command, {
          name: 'mongodb.Command',
          patchType: ASYNC_CONTEXT,
          alwaysRun: true,
          post: (data) => {
            hookMethod(data.result, 'executeCommand', 'mongodb.Command');
            hookMethod(data.result, 'execute', 'mongodb.Command');
          },
        });
      }
    }
  );

  requireHook.resolve(
    { name: 'mongodb', file: 'lib/cursor.js', version: '>=3.3.0' },
    (cursor, { version }) => {
      if (semver.lt(version, '4.0.0')) {
        return patcher.patch(cursor, {
          name: 'mongodb.Cursor',
          patchType: ASYNC_CONTEXT,
          alwaysRun: true,
          post: (data) => {
            hookMethod(data.result, '_next', 'mongodb.Cursor');
          },
        });
      }
    }
  );
}

module.exports = init;
module.exports.init = init;
