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

/**
 * [BIZ_FIN_164] 调价策略导致的毛利漂移分析 (Margin Drift)
 * @description 分析调价策略对毛利的影响，评估调价质量。
 */
export class PricingAuditService {
  private static readonly DRIFT_TABLE = 'cf_pricing_margin_drifts';

  /**
   * 分析毛利漂移
   */
  static async analyzeMarginDrift(tenantId: string, skuId: string) {
    logger.info(`[PricingAudit] Analyzing margin drift for SKU: ${skuId} for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的订单毛利趋势
    const trends = await db('cf_recon_records')
      .join('cf_consumer_orders', 'cf_recon_records.orderId', '=', 'cf_consumer_orders.id')
      .where({ 'cf_recon_records.tenantId': tenantId, 'cf_consumer_orders.productId': skuId })
      .select(
        db.raw('DATE(cf_recon_records.created_at) as date'),
        db.raw('AVG(cf_recon_records.netProfit / cf_recon_records.platformAmount) as avgMargin')
      )
      .groupBy('date')
      .orderBy('date', 'desc');

    if (trends.length < 2) return null;

    const latestMargin = Number(trends[0].avgMargin);
    const previousMargin = Number(trends[1].avgMargin);

    // 2. 识别漂移 (毛利下降 > 5%)
    const driftRatio = latestMargin - previousMargin;
    let status = 'STABLE';
    let alertMsg = 'Margin is stable';

    if (driftRatio < -0.05) {
      status = 'EROSION';
      alertMsg = `Margin eroded by ${(Math.abs(driftRatio) * 100).toFixed(2)}% compared to previous period. Check dynamic pricing rules.`;
    } else if (driftRatio > 0.05) {
      status = 'IMPROVEMENT';
      alertMsg = `Margin improved by ${(driftRatio * 100).toFixed(2)}%. Pricing strategy is effective.`;
    }

    const driftRecord = {
      id: `MD-${tenantId}-${skuId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      skuId,
      latestMargin: Number(latestMargin.toFixed(4)),
      driftRatio: Number(driftRatio.toFixed(4)),
      status,
      alertMsg,
      created_at: new Date()
    };

    // 3. 存储漂移记录
    await db(this.DRIFT_TABLE)
      .insert(driftRecord)
      .onConflict(['id'])
      .merge();

    return driftRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.DRIFT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.DRIFT_TABLE} table...`);
      await db.schema.createTable(this.DRIFT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('skuId', 128).notNullable();
        table.decimal('latestMargin', 10, 4);
        table.decimal('driftRatio', 10, 4);
        table.string('status', 20); // E.g., STABLE, EROSION, IMPROVEMENT
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'skuId']);
      });
    }
  }
}
