import { PlatformProduct } from '../core/connectors/IPlatformConnector';
import { PublishOrchestrator } from '../core/orchestrator/PublishOrchestrator';
import { TaskRecord, TaskStatus } from '../domains/Trade/TaskFSM';
import { logger } from '../utils/logger';
import { AuditService } from './AuditService';

/**
 * [CORE_INT_03] 发布服务
 * @description 封装发布业务逻辑，集成发布编排中心与审计
 */
export class PublishService {
  /**
   * 提交发布任务
   */
  static async submitPublishTask(params: {
    tenantId: string;
    shopId: string;
    productId: string;
    platform: string;
    productData: PlatformProduct;
    traceId: string;
  }): Promise<string> {
    const taskId = `PUB-${Date.now()}`;
    logger.info(`[PublishService] Submitting publish task: ${taskId} for Tenant: ${params.tenantId}`);

    const task: TaskRecord = {
      id: taskId,
      tenantId: params.tenantId,
      traceId: params.traceId,
      status: TaskStatus.APPROVED, // 假设已经通过审核
      retryCount: 0
    };

    // 1. 记录初始审计日志
    await AuditService.log({
      tenantId: params.tenantId,
      traceId: params.traceId,
      userId: 'system', // 添加 userId
      module: 'PUBLISH',
      action: 'SUBMIT_TASK',
      resourceType: 'product',
      resourceId: params.productId,
      metadata: { taskId, platform: params.platform, shopId: params.shopId },
      source: 'node', 
      result: 'success'
    });

    // 2. 异步启动编排流程
    // 注意：在真实生产环境应使用消息队列或背景任务
    PublishOrchestrator.startPublish(task, params.productData, params.platform, params.shopId)
      .catch(err => logger.error(`[PublishService] Async publish error for ${taskId}: ${err.message}`));

    return taskId;
  }

  /**
   * 处理从 Node Agent 回传的发布结果
   */
  static async handleNodeReceipt(receipt: any) {
    logger.info(`[PublishService] Handling receipt for Task: ${receipt.taskId}`);
    await PublishOrchestrator.handleReceipt(receipt);
  }
}
