import { Worker } from 'bullmq';
import { logger } from '../utils/logger';
import { AuditLogEntry } from './AuditService';
import db from '../config/database';

/**
 * @description 审计日志异步处理 Worker (CORE_DEV_04)
 */
export const startAuditWorker = () => {
  const worker = new Worker('audit-log', async (job) => {
    const entry: AuditLogEntry = job.data;
    
    try {
      // 1. 持久化到数据库 (V22.1)
      await db('cf_operation_log').insert({
        tenant_id: entry.tenantId,
        shop_id: entry.shopId,
        task_id: entry.taskId,
        trace_id: entry.traceId,
        user_id: entry.userId,
        role_code: entry.roleCode,
        module: entry.module,
        action: entry.action,
        resource_type: entry.resourceType,
        resource_id: entry.resourceId,
        before_snapshot: entry.beforeSnapshot ? JSON.stringify(entry.beforeSnapshot) : null,
        after_snapshot: entry.afterSnapshot ? JSON.stringify(entry.afterSnapshot) : null,
        result: entry.result,
        error_code: entry.errorCode,
        error_message: entry.errorMessage,
        client_ip: entry.clientIp,
        user_agent: entry.userAgent,
        source: entry.source,
        created_at: new Date(entry.timestamp)
      });

      logger.info(`[AuditWorker] Successfully processed operation log: ${entry.action}`);
    } catch (err: any) {
      logger.error(`[AuditWorker] Failed to persist audit log: ${err.message}`);
      throw err; // 触发 BullMQ 的重试机制
    }
  }, {
    connection: {
      host: process.env.REDIS_HOST || '127.0.0.1',
      port: parseInt(process.env.REDIS_PORT || '6379'),
    },
    concurrency: 5 // 限制并发数
  });

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

  return worker;
};
