/**
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('../../../core/logger')('contrast:sequelize:propagator');
const tracker = require('../../../tracker');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { CallContext, PropagationEvent, Signature } = require('../../models');
const TagRange = require('../../models/tag-range');
const tagRangeUtil = require('../../models/tag-range/util');
const { isTracked, getSequelizeString } = require('./utils');

/**
 * We apply the tag whenever there are tracked string arguments.
 * @param {string} str SQL statement with replace named paramerters
 * @returns {Map}  returns a ES6 Map which is an ordered object of key values pairs.
 */
function getPositions(str) {
  const positions = [];
  // need to find strings that start with : and grab string as key and position and store in Map (order is important)
  const len = str.length;
  let i = 0,
    pos = 0,
    key = '';
  while (i < len) {
    if (str[i] === ':') {
      pos = i;
      key = '';
      while (i < len) {
        if (
          str[i] === ' ' ||
          str[i] === ',' ||
          str[i] === ')' ||
          str[i] === ';'
        ) {
          // need to check for <space> <,> <)> or <;>
          key = key.substring(1); // strip off the leading ':'
          positions.push({ [key]: pos });
          key = '';
          break;
        } else {
          key = key.concat(str[i]);
        }
        ++i;
      }
    } else {
      ++i;
    }
  }
  if (key !== '') {
    // the key was the last item in the sql string
    key = key.substring(1); // strip off the leading ':'
    positions.push({ [key]: pos }); // add object is at the end of the sql string, note keys start with ':'
  }
  return positions;
}

module.exports.handle = function() {
  moduleHook.resolve(
    { name: 'sequelize', file: 'lib/sql-string.js' },
    (sqlstring) => {
      logger.debug('hooking sql-string.js');

      patcher.patch(sqlstring, 'formatNamedParameters', {
        name: 'sequelize/lib/sql-string',
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        post(data) {
          const trackingData = tracker.getData(data.result);
          if (!trackingData) {
            return;
          }

          // Using an array is better than a map since need to update other position values based on index NOT key.
          const positions = getPositions(data.args[0]); // this is an array of objects
          if (!positions.length) {
            return;
          }

          const [, replacements, timezone, dialect] = data.args;
          const len = positions.length; // micro optomized since used multiple times

          for (let i = 0; i < len; i++) {
            const key = Object.keys(positions[i])[0];
            // we don't need to run in a no instrumentation scope here since
            // patcher will do so automatically since we're in a post hook
            const escapedVal = getSequelizeString().escape(
              replacements[key],
              timezone,
              dialect,
              true // true is required to get format function behavior.
            );

            if (isTracked(replacements[key])) {
              tagRangeUtil.addInPlace(
                trackingData.tagRanges,
                new TagRange(
                  positions[i][key],
                  positions[i][key] + escapedVal.length - 1,
                  'sql-encoded'
                )
              );
            }
            //update the string replacement poisitions based on current val length - it's replacing a :key with the string
            if (i < len - 1) {
              for (let j = i + 1; j < len; j++) {
                const nextKey = Object.keys(positions[j])[0];
                positions[j] = {
                  [nextKey]:
                    positions[j][nextKey] - (key.length + 1) + escapedVal.length // add 1 for the ':'
                };
              }
            }
          }

          const event = new PropagationEvent({
            context: CallContext.create(data),
            parents: [trackingData.event],
            signature: new Signature(
              'sequelize/lib/sql-string.formatNamedParameters'
            ),
            source: 'P',
            tagRanges: trackingData.tagRanges,
            target: 'R'
          });

          trackingData.event = event;
        }
      });
    }
  );
};
