import { Queue } from "bullmq";
import { QUEUE_NAME } from "../constants";
import type { VideoJobData } from "../types";

function getConnectionOptions() {
  const url = process.env.REDIS_URL || "redis://localhost:6379";
  const parsed = new URL(url);
  return {
    host: parsed.hostname,
    port: Number(parsed.port) || 6379,
    username: parsed.username || undefined,
    password: parsed.password || undefined,
    maxRetriesPerRequest: null as null,
  };
}

let queue: Queue | null = null;

export function getRedisConnection() {
  return getConnectionOptions();
}

export function getVideoQueue(): Queue {
  if (!queue) {
    queue = new Queue(QUEUE_NAME, {
      connection: getConnectionOptions(),
    });
  }
  return queue;
}

export async function enqueueVideoJob(data: VideoJobData) {
  const q = getVideoQueue();
  await q.add("process-video", data, {
    attempts: 2,
    backoff: { type: "exponential", delay: 5000 },
    removeOnComplete: 100,
    removeOnFail: 200,
  });
}
