import db from '../config/database';
import { AuditService } from './AuditService';
import { AIService } from './AIService';

/**
 * [BIZ_FIN_17] 多维度资金回笼周期 (DSO) 优化建议
 * 负责分析租户的订单回款周期 (DSO)，并基于 AI 生成优化建议（如更换承运商、调整结算周期等）
 */
export class DSOOptimizerService {
  /**
   * 生成 DSO 优化建议
   */
  static async generateAdvice(tenantId: string, traceId: string): Promise<void> {
    // 1. 计算当前 DSO (模拟从 cf_orders 和 cf_payout_statements 计算平均回款时长)
    const currentDso = 14.5; // 假设当前 14.5 天
    const targetDso = 10.0;

    // 2. 调用 AI 分析瓶颈 (模拟调用 AIService)
    const analysis = await AIService.analyzeDSOBottleneck(tenantId);
    const advice = analysis.advice;
    const impact = analysis.estimatedImpact; // 预计提升的现金流金额

    // 3. 持久化建议记录
    await db.transaction(async (trx) => {
      const [id] = await trx('cf_dso_optimization').insert({
        tenant_id: tenantId,
        current_dso: currentDso,
        target_dso: targetDso,
        optimization_advice: advice,
        estimated_cashflow_impact: impact
      });

      // 审计记录
      await AuditService.log({
        tenant_id: tenantId,
        action: 'DSO_ADVICE_GENERATED',
        target_type: 'FINANCE_STRATEGY',
        target_id: id.toString(),
        trace_id: traceId,
        new_data: JSON.stringify({ currentDso, advice }),
        metadata: JSON.stringify({ impact })
      });
    });
  }

  /**
   * 获取租户最新的 DSO 建议
   */
  static async getLatestAdvice(tenantId: string) {
    return await db('cf_dso_optimization')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc')
      .first();
  }
}
