/**
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 { PATCH_TYPES } = require('../../constants');
const patcher = require('../patcher');
const HttpFramework = require('./http');

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

class Http2Framework extends HttpFramework {
  /**
   * @param {Agent} agent
   */
  constructor(agent) {
    super(agent, 'http2');
  }

  /**
   * @param {import('http2')} http2
   * @returns {import('http2')}
   */
  onRequire(http2) {
    patcher.patch(http2, 'createServer', {
      name: `${this.id}.createServer`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post: ({ args, result }) => this.handleServerCreate(args, result)
    });

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

    return http2;
  }

  /**
   * Emits a create event for the new Server instance.
   * @param {any[]} args The arguments passed to the Server constructor
   * @param {import('net').Server} server The http Server instance
   */
  handleServerCreate(args, server) {
    super.handleServerCreate(args, server);

    // Since the `Http2Server` class is not exported, we can patch it here after
    // creation.
    // NOTE: could we just patch `net.Server` here and in `http`?
    patcher.patch(server, 'listen', {
      name: `${this.id}.Http2Server.listen`,
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      pre: ({ args, obj }) => this.handleServerListen(args, obj)
    });
  }
}

module.exports = Http2Framework;
