/**
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 logger = require('../../core/logger')('hooks:hapi');
const patcher = require('../../hooks/patcher');
const { uniqueId } = require('../../util/route-info');
const agentEmitter = require('../../agent-emitter');
const { PATCH_TYPES } = require('../../constants');
const {
  constants: {
    EVENTS: { HAPI_ROUTES, HAPI_ADD_ROUTE }
  }
} = require('../../core/hapi');

class RouteCoverage {
  constructor() {
    this.routeInfos = {};
    this.registeredRoutes = new Map();
    this.registerRouteHandler();
  }

  /**
   * Registers handlers on handling a route to properly
   * emit coverage and patches the handler to emit observation
   */
  registerRouteHandler() {
    agentEmitter.on(HAPI_ROUTES, this.emitRouteCoverage.bind(this));
    agentEmitter.on(HAPI_ADD_ROUTE, this.registerAddRouteHandler.bind(this));
  }

  /**
   * Adds a uniqueId for a given route.path in a local map
   * patches `route.settings.handler` to emit route observation
   *
   * @param {Hapi.Route} route
   */
  registerAddRouteHandler(route) {
    const self = this;

    if (!this.registeredRoutes.has(route.path)) {
      this.registeredRoutes.set(route.path, uniqueId());
    }

    patcher.patch(route.settings, 'handler', {
      name: 'hapi.route.handler',
      patchType: PATCH_TYPES.ROUTE_COVERAGE,
      alwaysRun: true,
      pre(data) {
        const [request = {}] = data.args;
        self.emitRouteObservation(request._route);
      }
    });
  }

  /**
   * Generates all defined routes from either route Map(hapi 19+)
   * or route objects and emits a `route-discovery` event
   *
   * @param {Object} routes
   */
  emitRouteCoverage(routes) {
    /*
     * Hapi19 switched route storage Object->Map
     */
    if (routes instanceof Map) {
      routes.forEach((val, method) => {
        val.routes.forEach(({ route }) => {
          this.generateRouteInfo(route);
        });
      });
    } else {
      const methods = Object.keys(routes);
      methods.forEach((method) => {
        routes[method].routes.forEach(({ route }) => {
          this.generateRouteInfo(route);
        });
      });
    }

    agentEmitter.emit('route-discovery', this.routeInfos);
  }

  /**
   * emits a route-observation event with the proper
   * keys: verb, id. If id and verb are falsey
   * it will log a warning and not report a route-observation
   *
   * @param {Hapi.Route} route hapi route instance
   *
   */
  emitRouteObservation(route = {}) {
    const { method: verb, path: url } = route;
    const id = this.registeredRoutes.get(route.path);
    if (id && verb) {
      agentEmitter.emit('route-observation', { verb, id, url });
    } else {
      logger.warn(
        `Unable to report route observation. id ${id || '?'}, verb: ${verb ||
          '?'}`
      );
    }
  }

  /**
   * Formats each route. If the id for a given
   * uri path exists, it will add the method to
   * methods and change the
   * "signature" to be an array of methods
   *
   * @param {Hapi.Route} route a hapi route object
   *
   */
  generateRouteInfo(route) {
    const { path, method } = route;
    const id = this.registeredRoutes.get(path);

    if (this.routeInfos[id]) {
      this.routeInfos[id].methods.push(method);
      this.routeInfos[id].signature = this.createSignature({
        method: this.routeInfos[id].methods,
        path
      });
    } else {
      this.routeInfos[id] = {
        methods: [method],
        id,
        signature: this.createSignature({ method, path })
      };
    }
  }

  /**
   * Creates the signature with proper method and path
   * @param {Hapi.Route} route
   * @param {String|Array} route.method if array it will join by ", "
   * @param {String} route.path path of route
   * @return {String} a signature line server.route({ method....
   */
  createSignature({ method, path }) {
    let signature = 'server.route({ method: ';
    signature += Array.isArray(method)
      ? `["${method.join('", "')}"]`
      : `"${method}"`;

    signature += `, path: "${path}" })`;
    return signature;
  }
}

module.exports = RouteCoverage;
