import { NOTIFICATION_RMQ_DLQ, NOTIFICATION_RMQ_QUEUE } from '@app/contracts';
import { ChannelModel, connect } from 'amqplib';
import { ResolvedRabbitMqConfig } from '@app/common';

type Connect = (url: string, options?: Record<string, unknown>) => Promise<ChannelModel>;

export const notificationQueueArguments = {
  'x-dead-letter-exchange': '',
  'x-dead-letter-routing-key': NOTIFICATION_RMQ_DLQ,
};

export async function assertNotificationTopology(
  config: string | ResolvedRabbitMqConfig,
  connectToRabbit: Connect = connect as unknown as Connect,
): Promise<void> {
  const url = typeof config === 'string' ? config : config.url;
  const options = typeof config === 'string' ? undefined : config.socketOptions.connectionOptions;
  const connection = await connectToRabbit(url, options);
  try {
    const channel = await connection.createChannel();
    try {
      await channel.assertQueue(NOTIFICATION_RMQ_DLQ, { durable: true, autoDelete: false, exclusive: false });
      await channel.assertQueue(NOTIFICATION_RMQ_QUEUE, {
        durable: true,
        autoDelete: false,
        exclusive: false,
        arguments: notificationQueueArguments,
      });
    } finally {
      await channel.close();
    }
  } finally {
    await connection.close();
  }
}
