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

const logger = require('../../core/logger')('contrast:rules:protect');
const constants = require('../../constants');
const BaseSensor = require('../../hooks/frameworks/base');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const SinkEvent = require('../models/sink-event');
const { inspect } = require('util');

const { SINK_TYPES } = constants;
const ID = 'sequelize';

class SequelizeSensor extends BaseSensor {
  constructor(agent) {
    super({ id: ID, agent });
  }

  install({ ModuleHook }) {
    ModuleHook.resolve({ name: 'sequelize' }, (sequelize) => {
      logger.debug('Installling sequelize sensors');

      patcher.patch(sequelize.prototype, 'query', {
        name: 'sequelize.prototype',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        pre: (wrapCtx) => {
          const data = _.get(wrapCtx, 'args.0');

          let query;
          if (typeof data === 'string' || data instanceof String) {
            query = data;
          } else {
            ({ query } = data || {});
          }

          if (!query) {
            logger.debug(
              'unable to resolve query in sequelize sensor: %s',
              inspect(wrapCtx)
            );
          }

          const dialect = _.get(wrapCtx, 'obj.options.dialect');
          SequelizeSensor.emitSinkEvent(
            this.emitter,
            query,
            dialect,
            SINK_TYPES.SQL_QUERY
          );
        }
      });
    });

    return this;
  }

  static emitSinkEvent(emitter, data, dialect, type) {
    if (_.isEmpty(data)) {
      return;
    }
    const event = new SinkEvent({ data, id: ID, type });
    if (dialect) {
      event.tags.add(dialect);
    }
    emitter.emit('protect.sink', event);
  }
}

module.exports = SequelizeSensor;
