import db from '../config/database';
import { logger } from '../utils/logger';
import { DecisionExplainabilityEngine } from '../core/ai/DecisionExplainabilityEngine';

export interface FeeUpdate {
  platform: string;
  category: string;
  oldRate: number;
  newRate: number;
  effectiveDate: Date;
}

/**
 * [BIZ_OPS_158] 多平台佣金比例变动自动抓取建议 (Platform Fees)
 * @description 核心逻辑：识别各平台（Amazon, Temu, Shopify）佣金比例变动，自动更新成本模型并建议调价以保护利润红线。
 */
export class PlatformFeeWatcher {
  /**
   * 执行平台佣金变动审计
   */
  static async auditFeeChanges(tenantId: string, updates: FeeUpdate[]): Promise<any> {
    logger.info(`[FeeWatcher] Auditing platform fee changes for tenant: ${tenantId}`);

    try {
      const suggestions = [];

      for (const update of updates) {
        // 1. 识别利润侵蚀风险 (Erosion Risk)
        if (update.newRate > update.oldRate) {
          const impact = update.newRate - update.oldRate;
          const reason = `Platform ${update.platform} increased fee for category ${update.category} from ${(update.oldRate * 100).toFixed(1)}% to ${(update.newRate * 100).toFixed(1)}%. ` +
            `Direct impact on margin: -${(impact * 100).toFixed(1)}%.`;

          // 2. 识别受影响的商品
          const affectedProducts = await db('cf_product')
            .where({ tenant_id: tenantId, platform: update.platform })
            .select('id', 'price', 'purchase_price');

          for (const product of affectedProducts) {
            // 3. 校验利润红线 (V30.0 Redline: B2C < 20% Trigger Warning)
            const currentMargin = (product.price - product.purchase_price) / product.price;
            const projectedMargin = currentMargin - impact;

            if (projectedMargin < 0.20) {
              const advice = `${reason} Projected margin for SKU ${product.id} will fall to ${(projectedMargin * 100).toFixed(1)}%, breaching 20% redline. ` +
                `Suggesting a price increase of at least ${(impact * 1.2 * product.price).toFixed(2)} to compensate.`;

              // 4. [UX_XAI_01] 记录决策证据链
              await DecisionExplainabilityEngine.logDecision({
                tenantId,
                module: 'FEE_GOVERNANCE',
                resourceId: product.id,
                decisionType: 'PRICE_PROTECTION_SUGGESTION',
                causalChain: advice,
                factors: [
                  { name: 'FeeIncrease', value: impact, weight: 0.8, impact: 'NEGATIVE' },
                  { name: 'MarginHealth', value: projectedMargin, weight: 0.2, impact: 'NEGATIVE' }
                ],
                traceId: `fee-watch-${Date.now()}`
              });

              suggestions.push({
                productId: product.id,
                advice
              });
            }
          }
        }
      }

      return { success: true, count: suggestions.length, suggestions };
    } catch (err: any) {
      logger.error(`[FeeWatcher][FATAL] Fee audit failed: ${err.message}`);
      throw {
        category: 'Logic Conflict',
        rootCause: 'Failed to calculate margin erosion for affected products',
        mitigation: 'Verify product price and purchase_price data'
      };
    }
  }
}
