/**
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 { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { addTagRangesWithOffset, trackResult } = require('../common');

const propagate = function propagate(data) {
  const [{ dir, root, base, name, ext }] = data.args;
  const resultMeta = {
    method: 'path.format',
    offset: 0,
    parents: [],
    tagRanges: []
  };

  const beginning = dir || root;
  if (beginning) {
    addTagRangesWithOffset(resultMeta, beginning);

    resultMeta.offset += beginning.length;
    // If only `root` is provided or `dir` is equal to `root` then the platform separator will not be included.
    if (dir && dir !== root) resultMeta.offset += 1;
  }

  if (base) {
    addTagRangesWithOffset(resultMeta, base);
  } else {
    if (name) {
      addTagRangesWithOffset(resultMeta, name);
      resultMeta.offset += name.length;
    }
    if (ext) {
      addTagRangesWithOffset(resultMeta, ext);
    }
  }

  trackResult(resultMeta, data);
};

module.exports.handle = function handle() {
  moduleHook.resolve({ name: 'path' }, (path) => {
    for (const os of ['posix', 'win32']) {
      patcher.patch(path[os], 'format', {
        name: `path.${os}.format`,
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        post: propagate
      });
    }
  });
};
