/**
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 agentEmitter = require('../../agent-emitter');
const logger = require('../../core/logger')('contrast:restify:utils');
const { get } = require('lodash');
const {
  prototype: { decorateRequest }
} = require('../../hooks/frameworks/base');
const utils = module.exports;

/**
 * Registers a handler of the given type (pre/post) and which calls a callback
 * with the handler args in a try/catch.
 * @param {restify.Server} server
 * @param {string} type
 * @param {function} handler
 */
utils.registerSafeHandler = function(server, type, handler) {
  if (!server[type]) {
    logger.error('restify.Server method name not recognized: %s', type);
    return;
  }
  server[type](utils.makeSafeHandler(handler));
};

/**
 * Returns a server handler which invokes the provided callback with the handler
 * args in a try/catch.
 * @param {function} handler
 * @returns {function}
 */
utils.makeSafeHandler = function(handler) {
  return function contrastHandler(req, res, next) {
    try {
      handler(req, res);
    } catch (error) {
      logger.error('error executing handler: %o', error);
    }
    next();
  };
};

/**
 * Checks if `mapParams` is truthy and calls `utils.emitParams`
 *
 * @param {Object} params
 * @param {Object} params.options options to queryParser or bodyParser plugins
 * @param {IncomingMessage} params.req
 */
utils.emitMappedParams = function({ options, req }) {
  const mapParams = get(options, 'mapParams');
  if (mapParams === true) {
    return utils.emitParams({ req });
  }
};

/**
 * Checks if `req.params` has keys defined and emits `assess.params`
 * to wrap the object in a `SourceMembrane`
 *
 * @param {Object} params
 * @param {IncomingMessage} params.req
 */
utils.emitParams = function({ req }) {
  const params = get(req, 'params', {});
  if (Object.keys(params).length) {
    decorateRequest({ parameters: params });
    agentEmitter.emit('assess.params', req, 'params');
  }
};
