/**
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 { emitSendEvent } = require('../../../hooks/frameworks/common');
const logger = require('../../../core/logger')('contrast:hooks:restify');
const { isString } = require('../../../util/is-string');
const agentEmitter = require('../../../agent-emitter');
const {
  constants: {
    EVENTS: { SEND }
  }
} = require('../../../core/restify');

/**
 * Adds a post listeners to Response.prototype.__send
 * to emit a `send` event when the body is a string
 */
function registerResponseScanningHandler() {
  // data is from patcher so { args, obj, result }
  agentEmitter.on(SEND.POST, (data) => {
    const res = data.obj;
    const body = _.get(data, 'args.0.body');
    logger.debug(
      'hooked restify response send - %s',
      _.get(res, 'req.url', 'unknown')
    );

    if (isString(body)) {
      emitSendEvent(body.valueOf());
    }
  });
}

module.exports = registerResponseScanningHandler;
