/**
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 querystring = require('querystring');

const tracker = require('../../../tracker');
const tagRangeUtil = require('../../models/tag-range/util');
const Scopes = require('../../../core/async-storage/scopes');
const { CallContext, PropagationEvent, Signature } = require('../../models');

/**
 * Return a function that querystring.parse will use for unescaping
 * parts.  Wraps querystring.unescape and handles propagating and
 * adjusting tag ranges from the input string to the parts (which will
 * be added to the result object)
 *
 * @param {Object} data patcher data
 * @returns {Function} function the unescape function
 */
function getUnescapeWrapper(data, unescape) {
  const input = data.args[0];
  const { trackingData } = data;

  function unescapeWrapper(part) {
    let result;
    const start = input.indexOf(part, data.curPos);
    // any tag ranges overlapping current part?
    const tagRanges = tagRangeUtil.trim(
      trackingData.tagRanges,
      start,
      start + part.length - 1
    );

    // track the part w/ trimmed ranges if applicable
    if (tagRanges.length) {
      const tracked = tracker.track(part);
      if (tracked) {
        result = tracked.str;
        tracked.props.tagRanges = tagRanges;
      }
    } else {
      result = part;
    }

    // allow propagation through unescape
    result = Scopes.runInAllowAllScope(() => unescape(result));
    const resultData = tracker.getData(result);

    if (resultData) {
      resultData.event = new PropagationEvent({
        context: CallContext.create({
          ...data,
          obj: null,
          args: data.origArgs,
          result
        }),
        parents: [resultData.event],
        signature: new Signature(data.funcKey.split(':')[1]),
        source: 'P',
        tagRanges: resultData.tagRanges,
        target: 'R',
        untags: ['url-encoded']
      });
    }

    // update state
    data.curPos = start + part.length;

    return result;
  }

  return unescapeWrapper;
}

function pre(data) {
  const input = data.args[0];
  if (!input) {
    return;
  }
  const trackingData = tracker.getData(input);

  if (!trackingData) {
    return;
  }

  data.origArgs = [...data.args];
  data.args[1] = data.args[1] || '&';
  data.args[2] = data.args[2] || '=';
  data.curPos = 0;
  data.trackingData = trackingData;

  const unescape =
    data.args[3] && typeof data.args[3].decodeURIComponent === 'function'
      ? data.args[3].decodeURIComponent
      : querystring.unescape;

  data.args[3] = {
    ...data.args[3],
    decodeURIComponent: getUnescapeWrapper(data, unescape)
  };
}

module.exports.handle = {
  pre
};
