import { Job, Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';
import { logger } from '../utils/logger';

const REDIS_HOST = process.env.REDIS_HOST || '127.0.0.1';
const REDIS_PORT = Number(process.env.REDIS_PORT) || 6379;

const connection = new IORedis({
  host: REDIS_HOST,
  port: REDIS_PORT,
  maxRetriesPerRequest: null,
});

/**
 * [CORE_WORK_01] 容器化采集调度中心 (Worker Hub)
 * @description 统一管理 BullMQ 队列与 Worker，支持异步采集、发布与同步任务
 */
export class WorkerHub {
  private static queues: Record<string, Queue> = {};
  private static workers: Record<string, Worker> = {};

  /**
   * 初始化队列
   */
  static getQueue(name: string): Queue {
    if (!this.queues[name]) {
      this.queues[name] = new Queue(name, { connection: connection as any });
      logger.info(`[WorkerHub] Queue initialized: ${name}`);
    }
    return this.queues[name];
  }

  /**
   * 注册 Worker
   */
  static registerWorker(name: string, processor: (job: Job) => Promise<any>, concurrency: number = 5) {
    if (this.workers[name]) return;

    const worker = new Worker(name, processor, { 
      connection: connection as any,
      concurrency,
      removeOnComplete: { count: 100 },
      removeOnFail: { count: 500 }
    });

    worker.on('completed', (job) => {
      logger.info(`[WorkerHub] Job ${name}:${job.id} completed`);
    });

    worker.on('failed', (job, err) => {
      logger.error(`[WorkerHub] Job ${name}:${job?.id} failed: ${err.message}`);
    });

    this.workers[name] = worker;
    logger.info(`[WorkerHub] Worker registered: ${name} (concurrency: ${concurrency})`);
  }

  /**
   * 关闭所有连接
   */
  static async shutdown() {
    for (const worker of Object.values(this.workers)) {
      await worker.close();
    }
    for (const queue of Object.values(this.queues)) {
      await queue.close();
    }
    await connection.quit();
  }
}
