/**
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 { uniqueId } = require('../../util/route-info');
const agentEmitter = require('../../agent-emitter');
const patcher = require('../../hooks/patcher');
const moduleHook = require('../../hooks/require');
const { PATCH_TYPES } = require('../../constants');
const { funcInfo } = require('@contrast/fn-inspect');

class RouteCoverage {
  constructor(agent) {
    this.routes = new Map();
    this.appDir = agent.appInfo.appDir;
    moduleHook.resolve(
      { name: '@loopback/rest', file: 'dist/router/routing-table.js' },
      this.patchRoutingTable.bind(this)
    );
  }

  /**
   * Get the argument names for a route
   *
   * @param {Object} route
   *
   * @returns {string} string representation of params
   */
  getSignatureArgs(route) {
    if (!route.spec.parameters) {
      return '';
    }
    return route.spec.parameters.map((p) => p.name).join(', ');
  }

  /**
   * Get the file:funcname prefix for a signature
   *
   * @param {Object} route
   *
   * @returns {string} string representation of the sgnature prefix
   */
  getSignatureFunc(route) {
    const func = route._controllerName ? route._controllerCtor : route._handler;
    const finfo = funcInfo(func);
    const path = finfo.file.replace(`${this.appDir}/`, '');
    const suffix = route._controllerName
      ? `${route._controllerName}.${route._methodName}`
      : finfo.method;
    return `${path}:${suffix}`;
  }

  /**
   * create a signature from a route
   *
   * @param {Object} route
   *
   * @returns {string} the signature for the route
   */
  createSignature(route) {
    return `${this.getSignatureFunc(route)}(${this.getSignatureArgs(route)})`;
  }

  /**
   * Apply patches to loopback/rest routing-table.js
   *
   * @param {Object} xport the export object to patch
   */
  patchRoutingTable(xport) {
    const self = this;
    patcher.patch(xport.RoutingTable.prototype, 'registerRoute', {
      alwaysRun: true,
      patchType: PATCH_TYPES.ROUTE_COVERAGE,
      name: '@loopback/rest/RoutingTable.registerRoute',
      post(data) {
        const route = data.args[0];
        const signature = self.createSignature(route);
        if (!self.routes.has(signature)) {
          const id = uniqueId();
          self.routes.set(signature, id);
          agentEmitter.emit('route-discovery', { [id]: { signature, id } });
        }
      }
    });

    patcher.patch(xport.RoutingTable.prototype, 'find', {
      alwaysRun: true,
      patchType: PATCH_TYPES.ROUTE_COVERAGE,
      name: '@loopback/rest/RoutingTable.find',
      post(data) {
        const req = data.args[0];
        const route = data.result;
        // ExternalRoutes are express routes
        // they're still reported via the express hooks
        if (!route || route.constructor.name === 'ExternalRoute') {
          return;
        }
        const signature = self.createSignature(route);
        let id;
        if (!self.routes.has(signature)) {
          id = uniqueId();
          self.routes.set(signature, id);
          agentEmitter.emit('route-discovery', { [id]: { signature, id } });
        } else {
          id = self.routes.get(signature);
        }
        agentEmitter.emit('route-observation', {
          verb: route.verb,
          id,
          url: req.url
        });
      }
    });
  }
}

module.exports = RouteCoverage;
