/**
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 { get } = require('lodash');
const agentEmitter = require('../../agent-emitter');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const {
  constants: { EVENTS },
  utils
} = require('../../core/restify');
const ID = Symbol('contrastRouteId');
const { uniqueId, getHandlerName } = require('../../util/route-info');

/**
 * Creates a signature from handlers in route chain
 * Also adds a unique id to route for retrieval in `route-observation`
 *
 * @param {Object} route created within `router.mount` in restify
 */
function createSignature(route) {
  const handlers = get(route, 'chain').getHandlers();
  const argsText = handlers.map(getHandlerName).join(', ');
  const signature = `Server.${route.method.toLowerCase()}('${
    route.path
  }', ${argsText})`;
  const id = uniqueId();
  // assign to route so it can be retrieved when we observe a route
  route[ID] = id;
  return { id, signature };
}

/**
 * Patches `router.mount` to properly add a unique id, signature to
 * each route and emits a `route-discovery` event
 * @param {Server} server
 */
function discoveryPatches(server) {
  patcher.patch(server.router, 'mount', {
    name: 'server.router',
    patchType: PATCH_TYPES.ROUTE_COVERAGE,
    alwaysRun: true,
    post({ result: route }) {
      const { id, signature } = createSignature(route);
      const event = { [id]: { signature, id } };
      agentEmitter.emit('route-discovery', event);
    }
  });
}

/**
 * Adds a wrapper handler for `server.use` to get the route
 * from request and emit a `route-observation` event
 * @param {Server} server
 */
function observationPatches(server) {
  utils.registerSafeHandler(server, 'use', function(req, res, next) {
    const { route } = req;
    const { url, method: verb } = req;
    const id = route[ID];
    agentEmitter.emit('route-observation', { verb, id, url });
  });
}

/**
 * sets up patches for `router.mount` and a handler for `server.use`
 * @param {Server} server
 */
module.exports = function registerRouteCoverageHandler() {
  agentEmitter.on(EVENTS.CREATE_SERVER, (server) => {
    discoveryPatches(server);
    observationPatches(server);
  });
};
