/**
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 DIALECTS = [
  // 'db2',
  // 'mariadb',
  'mssql',
  'mysql',
  // 'oracle',
  'postgres',
  // 'snowflake',
  'sqlite',
];

module.exports.handle = function () {
  for (const dialect of DIALECTS) {
    const file = `lib/dialects/${dialect}/query-generator.js`;

    moduleHook.resolve(
      { name: 'sequelize', file },
      (_export) => {
        logger.debug('hooking %s', file);

        const name = `sequelize.${_export.name}.prototype.quoteIdentifier`;
        patcher.patch(_export.prototype, 'quoteIdentifier', {
          name,
          patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
          post(data) {
            const trackingData = tracker.getData(data.result);
            if (!trackingData) return;

            tagRangeUtil.addInPlace(
              trackingData.tagRanges,
              new TagRange(0, data.result.length - 1, 'sql-encoded')
            );

            const event = new PropagationEvent({
              context: CallContext.create(data),
              parents: [trackingData.event],
              signature: new Signature(name),
              source: 'P',
              tagRanges: trackingData.tagRanges,
              target: 'R'
            });

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