import { Worker } from "bullmq";
import { prisma } from "../db/prisma.js";
import { closeRedisConnection, redisConnection } from "../lib/redis.js";
import {
  PUSH_BROADCAST_JOB_NAME,
  PUSH_QUEUE_NAME,
  PUSH_SIGNAL_JOB_NAME
} from "../modules/queues/queue.constants.js";
import type { PushJobData } from "../modules/queues/queue.types.js";
import { broadcastNotification, notifyUsersForSignal } from "../modules/push/push.service.js";
import { env } from "../config/env.js";

const worker = new Worker<PushJobData>(
  PUSH_QUEUE_NAME,
  async (job) => {
    if (job.name === PUSH_SIGNAL_JOB_NAME && job.data.type === "signal") {
      return notifyUsersForSignal(job.data.signalId, { force: job.data.force });
    }

    if (job.name === PUSH_BROADCAST_JOB_NAME && job.data.type === "broadcast") {
      return broadcastNotification({
        title: job.data.title,
        body: job.data.body,
        url: job.data.url,
        tag: job.data.tag,
        renotify: job.data.renotify
      });
    }

    throw new Error(`Unsupported push job: ${job.name}`);
  },
  {
    connection: redisConnection,
    concurrency: env.PUSH_WORKER_CONCURRENCY
  }
);

worker.on("completed", (job) => {
  console.log(`[push-worker] completed ${job.id}`);
});

worker.on("failed", (job, error) => {
  console.error(`[push-worker] failed ${job?.id ?? "unknown"}`, error);
});

async function shutdown() {
  await worker.close();
  await closeRedisConnection();
  await prisma.$disconnect();
  process.exit(0);
}

process.on("SIGINT", () => {
  void shutdown();
});

process.on("SIGTERM", () => {
  void shutdown();
});
