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

class RouteCoverage {
  constructor() {
    moduleHook.resolve(
      { name: 'koa-router' },
      this.registerRouteHandler.bind(this)
    );
    moduleHook.resolve(
      { name: '@koa/router' },
      this.registerRouteHandler.bind(this)
    );
  }

  /**
   * Registers handlers on handling a route to properly
   * emit coverage and patches the handler to emit observation
   *
   * @param {Koa.Router} Router koa-router export
   * @param {Object} metadata package meta from `@contrast/require-hook`
   */
  registerRouteHandler(Router, metadata) {
    logger.debug(
      `%s module loaded. installing route discovery hooks`,
      metadata.name
    );

    patcher.patch(Router.prototype, 'register', {
      name: 'koaRouter.prototype',
      patchType: PATCH_TYPES.ROUTE_COVERAGE,
      alwaysRun: true,
      post: ({ args, result: layer }) => {
        const [path, methods] = args;

        // register will call itself recursively on each path in an array,
        // so we don't need to handle the outer call
        if (Array.isArray(path)) {
          return;
        }

        // koa calls register with an empty array only for "use". and if it changes then
        // "use" is better than "undefined".
        const m = methods.length === 0 ? ['use'] : methods;

        const id = this.emitRouteCoverage(path, m);

        // If middleware is given as an array, then the array gets re-used per-layer.
        // In that case, we only want to prepend our observation middleware once.
        //
        // NOTE: When more than one path is given as an arg, they will share a handler
        // and the closure only captures the first. Because the handler is (by definition) the same
        // for both paths, it may actually be correct to add an observation middleware for every
        // individual path to the same middleware stack, because the observation of one path
        // triggers the same handler as the others would have.
        layer.stack.unshift(this.routeObservationMiddleware.bind(this, id));
      }
    });
  }
  /**
   * 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, methods) {
    const event = {};
    const info = { signature: createSignature(url, methods) };
    const id = uniqueId();
    info.id = id;
    event[id] = info;
    agentEmitter.emit('route-discovery', event);
    return id;
  }

  /**
   * Defines an async handler to be added to front of layer stack
   *
   * @param {Koa.Context} ctx koa ctx
   * @param {Function} next
   */
  async routeObservationMiddleware(id, ctx, next) {
    const req = ctx.request;

    if (req) {
      const { url, method: verb } = req;
      agentEmitter.emit('route-observation', { verb, id, url });
    }

    await next();
  }
}

module.exports = RouteCoverage;
