const amqplib = require("amqplib");
const connectStr = "amqp://rabbit:rabbit123@rabbitmq";

(async () => {
  const conn = await amqplib.connect(connectStr);
  const channel = await conn.createChannel();
  const queue = "puppeteer";

  process.once("SIGINT", async () => {
    await channel.close();
    await connection.close();
  });

  await channel.assertQueue(queue);
  await channel.prefetch(1);

  await channel.consume(
    queue,
    async (message) => {
      try {
        await processMessage(channel, message);
      } catch (error) {
        console.error(error.message);
        channel.ack(message);
      }
    },
    {noAck: false}
  );

  console.log("[*] Running...");
})();

async function processMessage(channel, message) {
  try {
    const response = JSON.parse(message.content.toString());
    console.log("[x] RECEIVED", response);
    await require("./puppeteer")(response['data']);
    console.log("[v] DONE");
    channel.ack(message);
  } catch (error) {
    throw new Error(error.message);
  }
}
