import { Worker } from "bullmq";
import { env } from "../config/env.js";
import { prisma } from "../db/prisma.js";
import { closeRedisConnection, redisConnection } from "../lib/redis.js";
import {
  SIGNALS_QUEUE_NAME,
  SIGNALS_SNAPSHOT_JOB_NAME
} from "../modules/queues/queue.constants.js";
import { syncParserSignalsSnapshot } from "../modules/signals/parser-signals.service.js";

const worker = new Worker(
  SIGNALS_QUEUE_NAME,
  async (job) => {
    if (job.name !== SIGNALS_SNAPSHOT_JOB_NAME) {
      throw new Error(`Unsupported signals job: ${job.name}`);
    }

    return syncParserSignalsSnapshot(job.data);
  },
  {
    connection: redisConnection,
    concurrency: env.SIGNALS_WORKER_CONCURRENCY
  }
);

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

worker.on("failed", (job, error) => {
  console.error(`[signals-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();
});
