import { Queue, Worker, type JobsOptions } from "bullmq";
import { env } from "../core/env.js";
import { logger } from "../core/logger.js";

export type NotifyJob = {
  guildId: string;
  channelId: string;
  message: string;
};

const hasRedis = Boolean(env.REDIS_URL);
const connection = hasRedis ? { url: env.REDIS_URL! } : null;

export const notifyQueue = hasRedis
  ? new Queue<NotifyJob, void, "notify">("notify-queue", { connection: connection! })
  : null;

export const addNotifyJob = async (payload: NotifyJob, opts?: JobsOptions) => {
  if (!notifyQueue) return false;
  await notifyQueue.add("notify", payload, opts);
  return true;
};

export const startNotifyWorker = (
  handler: (job: NotifyJob) => Promise<void>,
): Worker<NotifyJob, void, "notify"> | null => {
  if (!connection) {
    logger.warn("REDIS_URL not set. BullMQ worker disabled.");
    return null;
  }

  return new Worker<NotifyJob, void, "notify">(
    "notify-queue",
    async (job) => {
      await handler(job.data);
    },
    { connection },
  );
};
