/**
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 BaseSensor = require('../../hooks/frameworks/base');
const constants = require('../../constants');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const { emitSinkEvent } = require('../../hooks/frameworks/common');

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

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

  install({ ModuleHook }) {
    ModuleHook.resolve(
      { name: 'mysql', file: 'lib/Connection.js' },
      (Connection) => {
        patcher.patch(Connection.prototype, 'query', {
          name: 'mysql.prototype',
          patchType: PATCH_TYPES.PROTECT_SINK,
          alwaysRun: true,
          pre: (wrapCtx) => {
            const sql = wrapCtx.args[0];
            emitSinkEvent(getQuery(sql), SINK_TYPES.SQL_QUERY, ID);
          }
        });
      }
    );

    return this;
  }
}

/**
 * Extracts the SQL text from the query data argument. The method allows
 * clients to pass a <code>String</code> or an <code>Object</code>.
 * @param {String|Object} data The <code>query</code> parameter
 * @returns {String}
 */
function getQuery(data) {
  return typeof data === 'object' && !(data instanceof String)
    ? (data.sql || '').toString()
    : (data || '').toString();
}

module.exports = MySQLSensor;
