import amqp from 'amqplib';

const { NODE_ENV } = process.env;

export class MainQueueService {

  async sendTaskToQueue(task: unknown, queueName: string) {
    console.log('sending a new task to queue...');
    const rabbitMQApi = NODE_ENV === 'development' ? 'localhost' : 'rabbitmq';
    const connection = await amqp.connect(`amqp://${rabbitMQApi}`, { heartbeat: 10 });
    const channel = await connection.createChannel();

    await channel.assertQueue(queueName);
    channel.sendToQueue(queueName, Buffer.from(JSON.stringify(task)));

    await channel.close();
    await connection.close();
    console.log('new task is sent');
  }
}
