/**
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 agentEmitter = require('../../agent-emitter');
const logger = require('../../core/logger')('contrast:express:route-coverage');
const Helpers = require('../../core/express/utils');
const constants = require('../../constants');
const { EVENTS, RouteCoverage } = Helpers;
const { HTTP_VERBS } = constants;

class ExpressRouteCoverage {
  constructor() {
    agentEmitter.on(EVENTS.ROUTER_USE, ExpressRouteCoverage.handleRouterUse);

    agentEmitter.on(
      EVENTS.ROUTER_ROUTE,
      ExpressRouteCoverage.handleRouterRoute
    );

    agentEmitter.on(
      EVENTS.ROUTER_METHOD,
      ExpressRouteCoverage.handleRouterMethod
    );

    agentEmitter.on(EVENTS.APP_USE, ExpressRouteCoverage.handleAppUse);
    agentEmitter.on(EVENTS.APP_USE, ExpressRouteCoverage.handleAppMethod);

    agentEmitter.on(EVENTS.SERVER_LISTEN, ExpressRouteCoverage.discoverRoutes);
  }

  static handleRouterUse(framework, wrapCtx) {
    const { args } = wrapCtx;
    const router = wrapCtx.obj;
    const routers = Helpers.resolveRouters(args);

    if (!routers || !routers.length) {
      return;
    }

    RouteCoverage.handleDiscoveryEvent(framework, EVENTS.ROUTER_USE, {
      args,
      router,
      routers
    });
  }

  static handleRouterRoute(framework, wrapCtx) {
    const { args, result: route, obj } = wrapCtx;
    RouteCoverage.handleDiscoveryEvent(framework, EVENTS.ROUTER_ROUTE, {
      stack: obj.stack,
      args,
      route
    });
  }

  static handleRouterMethod(framework, wrapCtx, verb) {
    const { args, result: router } = wrapCtx;
    const layer = Helpers.getLastLayer(router);

    if (!layer || !layer.route || !layer.route.stack) {
      return;
    }

    const stack = ExpressRouteCoverage.filterValidHttpMethods(
      layer.route.stack
    );

    RouteCoverage.handleDiscoveryEvent(framework, EVENTS.ROUTER_METHOD, {
      router,
      args,
      layer,
      stack,
      verb
    });
  }

  static handleAppUse(framework, wrapCtx) {
    const { args, obj: router } = wrapCtx;
    RouteCoverage.handleDiscoveryEvent(framework, EVENTS.APP_USE, {
      args,
      router
    });
  }

  static handleAppMethod(framework, wrapCtx, verb) {
    const { args, result: app = {} } = wrapCtx;

    // express internally calls .get for things that
    // are not routes (e.g. https://github.com/expressjs/express/blob/master/lib/application.js#L144)
    if (verb === 'get' && args.length === 1) {
      return;
    }

    const layer = Helpers.getLastLayer(app._router);

    if (!layer || !layer.route || !layer.route.stack) {
      return;
    }

    const stack = ExpressRouteCoverage.filterValidHttpMethods(
      layer.route.stack
    );

    RouteCoverage.handleDiscoveryEvent(framework, EVENTS.APP_METHOD, {
      app,
      args,
      layer,
      stack,
      verb
    });
  }

  static discoverRoutes(framework, stack) {
    logger.debug('traversing Application stack for coverage discovery');

    RouteCoverage.discoverRoutes(framework, stack);
  }

  /**
   * Filters out only valid route methods see: HTTP_VERBS in lib/constants
   * @param {Array} stack an express stack
   */
  static filterValidHttpMethods(stack) {
    return stack.filter(
      (l) => l.method && l.method.toUpperCase() in HTTP_VERBS
    );
  }
}

module.exports = ExpressRouteCoverage;
