import { Worker } from "bullmq";
import { redisConnectionOpts } from "../connection.js";
import { sendVerification, sendPasswordReset } from "../../lib/email.js";
import { logger } from "../../lib/logger.js";

const log = logger.child({ component: "mail-worker" });

export function startMailWorker(): Worker {
  const worker = new Worker(
    "mail",
    async (job) => {
      log.info({ jobId: job.id, jobName: job.name }, `Processing mail job`);
      switch (job.name) {
        case "sendVerification":
          await sendVerification(job.data.email as string, job.data.token as string);
          break;
        case "sendPasswordReset":
          await sendPasswordReset(job.data.email as string, job.data.token as string);
          break;
        default:
          throw new Error(`Unknown mail job: ${job.name}`);
      }
      log.info({ jobId: job.id, jobName: job.name }, `Mail job completed`);
    },
    { connection: redisConnectionOpts },
  );

  worker.on("failed", (job, err) => {
    log.error({ jobId: job?.id, jobName: job?.name, err: err.message }, `Mail job failed`);
  });

  return worker;
}
