import { Worker } from 'bullmq';
import { processJob } from './processor';

let worker: Worker | null = null;

// 创建Worker
export const startWorker = (): void => {
  worker = new Worker(
    'core-queue',
    async job => {
      console.log(`[BullMQ Worker] Processing job: ${job.name}`, job.id);
      return await processJob(job);
    },
    {
      connection: {
        host: 'localhost',
        port: 6379
      },
      concurrency: 5,
      limiter: {
        max: 20,
        duration: 1000
      }
    }
  );

  // 监听Worker事件
  worker.on('completed', (job) => {
    console.log(`[BullMQ Worker] Job completed: ${job.id}`);
  });

  worker.on('failed', (job, error) => {
    console.error(`[BullMQ Worker] Job failed: ${job?.id}`, error);
  });

  worker.on('error', (error) => {
    console.error(`[BullMQ Worker] Worker error:`, error);
  });
};

export { worker };
