/**
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 patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const { createSignature, uniqueId } = require('../../util/route-info');
const agentEmitter = require('../../agent-emitter');
const {
  prototype: { decorateRequest }
} = require('../../hooks/frameworks/base');
const {
  constants: { EVENTS }
} = require('../../core/fastify');

const { get } = require('lodash');

class RouteCoverage {
  /**
   * Implements a fastify hook for `onRoute`
   */
  constructor() {
    // used for referencing route IDs during observation
    this.routeMap = {};
    RouteCoverage.methods.forEach((method) => {
      this.routeMap[method] = {};
    });

    agentEmitter.on(EVENTS.ON_ROUTE, this.registerRouteHandler.bind(this));
  }

  /**
   * Registers handlers on handling a route to properly
   * emit coverage and patches the handler to emit observation
   *
   * @param {Fastify.routeOptions} routeOptions properties of a route defintion
   */
  registerRouteHandler(routeOptions) {
    const self = this;
    if (!routeOptions || !routeOptions.method || !routeOptions.url) return;

    const url = `${get(routeOptions, 'prefix', '')}${routeOptions.url}`;

    if (Array.isArray(routeOptions.method)) {
      routeOptions.method.forEach((method) => {
        this.emitRouteCoverage(url, method);
      });
    } else {
      this.emitRouteCoverage(url, routeOptions.method);
    }

    patcher.patch(routeOptions, 'handler', {
      name: 'coverage',
      patchType: PATCH_TYPES.ROUTE_COVERAGE,
      alwaysRun: true,
      pre(data) {
        const [request] = data.args;
        const { method } = request.raw;
        self.emitObservation(method, url);
      }
    });
  }

  /**
   * emit the route coverage event
   * @param {string} url the route registered url
   * @param {string} method http method route is registered
   * @return {string} id used when observation occurs before discovery
   */
  emitRouteCoverage(url, method) {
    method = method.toLowerCase();
    const event = {};
    const info = { signature: createSignature(url, [method]) };
    const id = uniqueId();
    info.id = id;
    event[id] = info;
    agentEmitter.emit('route-discovery', event);
    this.routeMap[method][url] = { id };
  }

  /**
   * emit route observation event
   * @param {string} verb http method route is registered
   * @param {string} url the route registered url
   */
  emitObservation(verb, url) {
    // fastify methods are in lowercase and teamserver doesn't mind method case
    verb = verb.toLowerCase();
    const { id } = this.routeMap[verb][url];
    decorateRequest({ normalizedUri: url });
    agentEmitter.emit('route-observation', { verb, url, id });
  }
}

// see fastify/lib/route.js supportedMethods
RouteCoverage.methods = [
  'delete',
  'get',
  'head',
  'patch',
  'post',
  'put',
  'options',
  'all'
];

module.exports = RouteCoverage;
