const Queue = require("better-queue");
const moment = require("moment");
const { client } = require("../graphql-client/graphql-client");
const { UPDATE_TASKS_REMIND_AT_SENT } = require("../graphql-client/queries");
const logger = require("../utils/logger");
const taskEmailQueue = () =>
  new Queue(
    (taskIds, cb) => {
      logger.log("Processing reminds for taskIds: ", "silly", null, null, {
        taskIds: taskIds?.join(", ")
      });
      // Set the remind_at_sent to the current time.
      const now = moment().toISOString();

      client
        .request(UPDATE_TASKS_REMIND_AT_SENT, { taskIds, now })
        .then((taskResponse) => {
          logger.log("task-remind-email-queue", "info", null, null, taskResponse);
          cb(null, taskResponse);
        })
        .catch((err) => {
          logger.log("task-remind-email-queue", "error", null, null, err);
          cb(err);
        });
    },
    {
      batchSize: 50,
      batchDelay: 5000,
      // The lower this is, the more likely we are to hit the rate limit.
      batchDelayTimeout: 1000
    }
  );

module.exports = { taskEmailQueue };
