/**
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 tracker = require('../../../tracker');
const patcher = require('../../../hooks/patcher');
const requireHook = require('../../../hooks/require');
const tagRangeUtil = require('../../models/tag-range/util');
const {
  PATCH_TYPES: { ASSESS_PROPAGATOR }
} = require('../../../constants');
const {
  hasUserDefinedValidator,
  tagCustomValidatedValues
} = require('./helpers');
const agent = require('../../../agent');

const doValidateSyncPatcher = (SchemaMap) => {
  patcher.patch(SchemaMap.prototype, 'doValidateSync', {
    alwaysRun: true,
    name: 'mongoose.mixed.doValidateSync',
    patchType: ASSESS_PROPAGATOR,
    post(data) {
      if (data.result || !hasUserDefinedValidator(data)) return;

      const input = data.args[0];
      const inputType = typeof input;

      if (inputType !== 'string' && inputType !== 'object') return;

      let values;
      if (inputType === 'string') {
        values = [input];
      } else if (Array.isArray(input)) {
        values = input;
      } else if (input instanceof Map) {
        values = input.values();
      } else {
        values = Object.values(input);
      }

      tagCustomValidatedValues(values, data, tracker, tagRangeUtil);
    }
  });
};

requireHook.resolve(
  { name: 'mongoose', file: 'lib/schema/mixed.js', version: '>=5.0.0' },
  (SchemaMap) => {
    if (
      !agent.config ||
      (agent.config && !agent.config.assess.trust_custom_validators)
    ) {
      return;
    }

    doValidateSyncPatcher(SchemaMap);
  }
);
