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

/**
 * [BIZ_ECO_02] 基于博弈论的供应商价值共享模型 (Eco Value Sharing)
 * 负责在租户与供应商之间，基于历史表现、利润贡献与风险承担，利用博弈论模型自动分配额外增值收益
 */
export class EcoValueSharingService {
  /**
   * 计算并执行价值分配
   */
  static async calculateAndShare(
    tenantId: string, 
    supplierId: string, 
    totalIncrementalProfit: number, 
    traceId: string
  ): Promise<number> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_ECO_VALUE_SHARING', tenantId))) {
      return 0;
    }
    // 1. 获取博弈因子 (租户忠诚度、供应商交期稳定性、质量分)
    // 模拟数据：替代 AIService.getEcoGameFactors
    const gameFactors = {
      tenantLoyalty: 0.85,
      supplierDeliveryStability: 0.92,
      qualityScore: 0.95
    };
    
    // 2. 运行博弈论分配模型 (Shapley Value 或 Nash Equilibrium 模拟)
    // 模拟数据：替代 AIService.runValueSharingGame
    const supplierShare = totalIncrementalProfit * 0.3; // 假设供应商分享30%
    const sharingLogic = {
      supplierAmount: supplierShare,
      tenantAmount: totalIncrementalProfit - supplierShare,
      model: 'Nash Equilibrium',
      factors: gameFactors
    };

    await db.transaction(async (trx) => {
      // 3. 记录分配快照
      const [id] = await trx('cf_eco_value_sharing').insert({
        tenant_id: tenantId,
        supplier_id: supplierId,
        shared_profit_amount: supplierShare,
        sharing_logic: JSON.stringify(sharingLogic),
        status: 'CALCULATED'
      });

      // 4. 执行资金拨付 (模拟)
      await trx('cf_eco_value_sharing')
        .where({ id })
        .update({
          status: 'TRANSFERRED',
          updated_at: db.fn.now()
        });

      // 5. 审计记录
      await AuditService.log({
        tenantId: tenantId,
        userId: 'SYSTEM_BOT',
        module: 'ECO_VALUE_SHARING',
        action: 'ECO_VALUE_SHARED',
        resourceType: 'SUPPLIER_RELATION',
        resourceId: supplierId,
        traceId: traceId,
        afterSnapshot: JSON.stringify({ sharedAmount: supplierShare, totalProfit: totalIncrementalProfit }),
        result: 'success',
        source: 'node',
        metadata: { model: 'Nash Equilibrium' }
      });
    });

    return supplierShare;
  }

  /**
   * 获取租户所有价值共享记录
   */
  static async getSharingHistory(tenantId: string) {
    return await db('cf_eco_value_sharing')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
