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

/**
 * [BIZ_AUTO_16] 基于库存周转率的自动补货策略自优化
 * 负责利用强化学习 (RL) 自动调整 SKU 的再订货点 (Reorder Point)，平衡缺货风险与资金占用
 */
export class InventoryRLService {
  /**
   * 运行 RL 优化补货策略
   */
  static async optimizeReorderPoint(tenantId: string, productId: string, traceId: string): Promise<void> {
    // 1. 获取该产品的历史周转数据
    const inventory = await db('cf_inventory').where({ tenant_id: tenantId, product_id: productId }).first();
    if (!inventory) return;

    // 2. 调用 AI (RL Agent) 计算最优补货点 (模拟调用 RL 优化引擎)
    const currentReorderPoint = 50; // 假设当前为 50
    const optimization = await AIService.optimizeInventoryPolicy(tenantId, productId, currentReorderPoint);
    const newReorderPoint = optimization.suggestedPoint;
    const improvementScore = optimization.expectedScore;

    if (newReorderPoint !== currentReorderPoint) {
      await db.transaction(async (trx) => {
        // 记录优化记录
        const [id] = await trx('cf_inventory_rl').insert({
          tenant_id: tenantId,
          product_id: productId,
          turnover_rate: 0.15, // 模拟周转率
          old_reorder_point: currentReorderPoint,
          new_reorder_point: newReorderPoint,
          improvement_score: improvementScore
        });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'INVENTORY_POLICY_OPTIMIZED',
          target_type: 'INVENTORY_STRATEGY',
          target_id: id.toString(),
          trace_id: traceId,
          new_data: JSON.stringify({ old: currentReorderPoint, new: newReorderPoint }),
          metadata: JSON.stringify({ improvementScore })
        });
      });
    }
  }

  /**
   * 获取租户所有补货策略优化历史
   */
  static async getOptimizationHistory(tenantId: string) {
    return await db('cf_inventory_rl')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
