import { logger } from '../../utils/logger';
import { SupplyChainService } from '../../services/SupplyChainService';
import { InventoryForecastService } from '../../services/InventoryForecastService';
import { DynamicPricingService } from '../../services/DynamicPricingService';

/**
 * [V31.3] Shadow Auditing Service
 * @description AI-2 (Internal) 负责对 AI-1 和 AI-3 的核心功能进行影子测试（最小冒烟测试），确保逻辑闭环。
 */
export class ShadowAuditService {
  /**
   * 执行全量影子测试
   */
  static async runAllAudits(tenantId: string) {
    logger.info(`[ShadowAudit] Starting full audit for tenant: ${tenantId}`);
    
    const results = {
      routing: await this.auditRouting(tenantId),
      forecast: await this.auditForecast(tenantId),
      pricing: await this.auditPricing(tenantId)
    };

    logger.info(`[ShadowAudit] Audit complete: ${JSON.stringify(results)}`);
    return results;
  }

  /**
   * [AI-1] 供应路由测试 (BIZ_SUP_15)
   */
  private static async auditRouting(tenantId: string) {
    try {
      // 验证寻源建议是否能正常生成且记录因果链
      const result = await SupplyChainService.traceSourceFactory(tenantId, 'TEST-PROD-001', 'https://example.com/image.jpg');
      return { status: 'PASSED', suggestionId: result.suggestionId };
    } catch (err: any) {
      return { status: 'FAILED', error: err.message };
    }
  }

  /**
   * [AI-3] 销量预测测试 (BIZ_INV_10)
   */
  private static async auditForecast(tenantId: string) {
    try {
      // 验证补货建议是否能正常生成
      const result = await InventoryForecastService.predictReplenishment(tenantId, 'TEST-PROD-001');
      return { status: 'PASSED', replenishmentQty: result.suggestedQty };
    } catch (err: any) {
      return { status: 'FAILED', error: err.message };
    }
  }

  /**
   * [AI-1] 动态调价测试 (BIZ_MKT_30)
   */
  private static async auditPricing(tenantId: string) {
    try {
      // 验证调价决策是否能正常生成
      const decision = await DynamicPricingService.generatePricingDecision(tenantId, 'TEST-SHOP-001', 'TEST-PROD-001');
      return { status: 'PASSED', decisionId: decision.id };
    } catch (err: any) {
      return { status: 'FAILED', error: err.message };
    }
  }
}
