import { getNextJob, updateJob, Job } from './jobQueue';
import { emitEvent } from './eventBus';

const processJob = async (job: Job): Promise<void> => {
  try {
    updateJob(job.id, { status: 'running' });
    
    console.log(`[Worker] Processing job: ${job.type}`, job.id);
    
    // 模拟不同类型任务的处理
    switch (job.type) {
      case 'AI_OPTIMIZE_PRODUCT':
        // 模拟AI处理
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        emitEvent('AI_TASK_COMPLETED', {
          productId: job.payload.productId
        }, 'Worker', job.merchantId);
        break;
        
      case 'SYNC_INVENTORY':
        // 模拟库存同步
        await new Promise(resolve => setTimeout(resolve, 500));
        
        emitEvent('INVENTORY_UPDATED', {}, 'Worker');
        break;
        
      case 'CALCULATE_PROFIT':
        // 模拟利润计算
        await new Promise(resolve => setTimeout(resolve, 800));
        break;
        
      case 'GENERATE_BILL':
        // 模拟账单生成
        await new Promise(resolve => setTimeout(resolve, 500));
        
        emitEvent('BILLING_GENERATED', {
          merchantId: job.merchantId
        }, 'Worker', job.merchantId);
        break;
        
      default:
        console.log(`[Worker] Unknown job type: ${job.type}`);
        break;
    }
    
    updateJob(job.id, { 
      status: 'success',
      result: { completedAt: Date.now() }
    });
    
    emitEvent('JOB_COMPLETED', {
      jobId: job.id,
      jobType: job.type
    }, 'Worker', job.merchantId);
    
  } catch (error) {
    console.error(`[Worker] Error processing job ${job.id}:`, error);
    
    const updatedJob = updateJob(job.id, {
      status: 'failed',
      retryCount: job.retryCount + 1
    });
    
    if (updatedJob && updatedJob.retryCount < 3) {
      // 重试机制
      setTimeout(() => {
        updateJob(job.id, { status: 'pending' });
      }, 5000);
    }
    
    emitEvent('JOB_FAILED', {
      jobId: job.id,
      jobType: job.type,
      error: (error as Error).message
    }, 'Worker', job.merchantId);
  }
};

export const startWorker = (): void => {
  console.log('[Worker] Starting worker...');
  
  setInterval(async () => {
    const job = getNextJob();
    
    if (job) {
      await processJob(job);
    }
  }, 1000);
};

export default {
  startWorker,
  processJob
};
