/**
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';

class MessageQueueClient {
  constructor({ agent }) {
    this.agent = agent;
    this.exchangeType = 'direct';
    this.mqLocation = this.agent.config.get(
      'agent.node.dev.screener.mq_location'
    );
    this.exchangeName = this.agent.config.get(
      'agent.node.dev.screener.exchange_name'
    );
  }

  /**
   * Connects to mq server and constructs a channel for exchange comms.
   * Compositionally this should occur during onboarding. So if this fails, we
   * should catch the promise rejection downstream and start w/out
   * instrumentation.
   */
  async initialize() {
    const { exchangeName, exchangeType } = this;
    this.connectionManager = require('amqp-connection-manager');
    this.connection = await this.connectionManager.connect(this.mqLocation);
    this.channel = await this.connection.createChannel();
    this.channel.assertExchange(exchangeName, exchangeType, {
      durable: false
    });
    await this.channel.waitForConnect();
  }

  /**
   * Ensures channel and publishes message to exchange with queue id.
   * @param {Object} params
   * @param {string} params.queueId name of queue to publish message
   * @param {Buffer} params.message buffer of stringified protobuf object
   */
  async send({ queueId, message }) {
    const { exchangeName } = this;
    await this.channel.publish(exchangeName, queueId, message);
    return {};
  }
}

module.exports = MessageQueueClient;
