/**
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 patcher = require('../../../hooks/patcher');
const requireHook = require('../../../hooks/require');
const {
  PATCH_TYPES: { ASSESS_PROPAGATOR },
} = require('../../../constants');
const { isObject } = require('../utils');

requireHook.resolve(
  { name: 'joi', file: 'lib/types/keys.js', version: '>=17.0.0' },
  (joi) => {
    patcher.patch(joi.__proto__, 'keys', {
      name: 'joi.keys',
      alwaysRun: true,
      patchType: ASSESS_PROPAGATOR,
      pre(data) {
        if (!data || !data.args) return;
        const value = data.args[0];
        if (value) {
          traverseObject(data.obj.$_root, value, value);
        }
      },
    });
  }
);

const traverseObject = (joi, currentValue, originalInput, currentPath = []) => {
  if (joi.isSchema(currentValue) || joi.isExpression(currentValue)) return;
  if (joi.isRef(currentValue)) {
    const referenceInstance = currentValue;

    const targetSchemaInstace = currentValue.path.reduce(
      (acc, value) => acc[value] || acc,
      originalInput
    );

    if (!targetSchemaInstace) return;

    if (!targetSchemaInstace.__CONTRAST__) {
      Object.defineProperty(targetSchemaInstace, '__CONTRAST__', {
        enumerable: false,
        configurable: true,
        value: {
          refInstances: {},
        },
        writable: true,
      });
    }

    targetSchemaInstace.__CONTRAST__.refInstances[currentPath.join('.')] = referenceInstance;
  }

  if (isObject(currentValue)) {
    for (const [objKey, objValue] of Object.entries(currentValue)) {
      traverseObject(joi, objValue, originalInput, [...currentPath, objKey]);
    }
  }
};
