import { Queue } from 'bullmq';
import { calculateCompositePriority } from './queue/priority';

let jobQueue: Queue | null = null;

// 创建队列
const createQueue = (): Queue => {
  return new Queue('core-queue', {
    connection: {
      host: 'localhost',
      port: 6379
    },
    defaultJobOptions: {
      attempts: 3,
      backoff: { type: 'exponential', delay: 1000 },
      removeOnComplete: 1000,
      removeOnFail: 10000
    }
  });
};

// 生成唯一的Job ID
export const generateJobId = (type: string, data: any): string => {
  const uniqueKey = data.productId || data.merchantId || Date.now();
  return `${type}-${uniqueKey}-${Date.now()}`;
};

// 添加任务到队列
export const addJob = async (name: string, data: any, options?: any): Promise<any> => {
  if (!jobQueue) {
    jobQueue = createQueue();
  }
  
  const jobId = generateJobId(name, data);
  
  // 计算综合优先级
  const priority = calculateCompositePriority(
    name,
    data.roi || 0,
    data.merchantId || 'anonymous',
    data.businessType || 'TOC'
  );
  
  return await jobQueue.add(name, data, {
    priority,
    delay: options?.delay || 0,
    jobId,
    ...options
  });
};

// 获取队列实例
export const getQueue = (): Queue => {
  if (!jobQueue) {
    jobQueue = createQueue();
  }
  return jobQueue;
};

export default {
  getQueue,
  addJob,
  generateJobId
};

