/**
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 BaseFramework = require('./base');
const moduleHook = require('../require');
const patcher = require('../patcher');
const { HTTP_EVENTS, PATCH_TYPES } = require('../../constants');

/** @typedef {import('../../agent').ContrastAgent} Agent */
/** @typedef {import('net').Server} Server */

class HttpFramework extends BaseFramework {
  /**
   * @param {Agent} agent
   * @param {string} id
   */
  constructor(agent, id = 'http') {
    super({ agent, id });
    moduleHook.resolve({ name: this.id }, this.onRequire.bind(this));
  }

  /**
   * @template {import('http') | import('https')} T
   * @param {T} xport
   * @returns {T}
   */
  onRequire(xport) {
    patcher.patch(xport, 'Server', {
      name: `${this.id}.Server`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post: (fnData) => this.handleServerCreate(fnData.args, fnData.result)
    });

    patcher.patch(xport, 'createServer', {
      name: `${this.id}.createServer`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post: (fnData) => this.handleServerCreate(fnData.args, fnData.result)
    });

    patcher.patch(xport.Server.prototype, 'listen', {
      name: `${this.id}.Server.prototype`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      pre: (fnData) => this.handleServerListen(fnData.args, fnData.obj)
    });

    return xport;
  }

  /**
   * Emits a listen event if one has not been pubished for the server instance.
   * @param {any[]}
   * @param {Server} server Server on which `listen` was called
   */
  handleServerListen(args, server) {
    this.emitter.emit(HTTP_EVENTS.SERVER_LISTEN, args, server);
  }

  /**
   * Emits a create event for the new Server instance.
   * @param {any[]} args The arguments passed to the Server constructor
   * @param {Server} server The http Server instance
   */
  handleServerCreate(args, server) {
    const [options] = args;
    let [, handler] = args;
    if (typeof options === 'function') {
      handler = options;
    }
    this.emitter.emit(HTTP_EVENTS.SERVER_CREATE, handler, server);
  }
}

module.exports = HttpFramework;
