import db from '../../config/database';
import { logger } from '../../utils/logger';
import { PricingService, ProfitSnapshot } from '../../services/PricingService';

/**
 * [BIZ_FIN_08] 实时毛利计算与分账引擎 (Settlement Engine)
 * @description 核心逻辑：实现订单级 P&L 穿透分析、动态成本分摊及财务分账。
 */
export class SettlementService {
  private static readonly TABLE_NAME = 'cf_profit_loss_snapshots';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('order_id', 64).primary();
        table.string('tenant_id', 64).notNullable().index();
        table.decimal('selling_price', 15, 2);
        table.decimal('purchase_price', 15, 2);
        table.decimal('platform_fee', 15, 2);
        table.decimal('logistics_cost', 15, 2);
        table.decimal('tax', 15, 2);
        table.decimal('fx_hedging', 15, 2);
        table.decimal('after_sales_loss', 15, 2);
        table.decimal('ad_amortization', 15, 2);
        table.decimal('net_profit', 15, 2);
        table.decimal('roi', 10, 4);
        table.decimal('profit_rate', 10, 4);
        table.json('metadata'); // 动态分摊成本详情
        table.timestamps(true, true);
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 计算并存储订单 P&L 快照
   */
  static async settleOrder(tenantId: string, orderId: string): Promise<ProfitSnapshot> {
    const order = await db('cf_consumer_orders').where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error(`Order ${orderId} not found`);

    // 1. 调用 PricingService 计算基础毛利
    // 实际业务中，purchasePrice 和 logisticsCost 应由 SupplyChainService 提供或从 order.profit_snapshot 读取
    const snapshot = await PricingService.calculateNetProfit({
      sellingPrice: order.total_amount,
      purchasePrice: order.profit_snapshot?.purchasePrice || (order.total_amount * 0.4), // Mock 40% cost
      platform: order.platform,
      countryCode: order.site,
      logisticsCost: order.profit_snapshot?.logisticsCost || (order.total_amount * 0.1), // Mock 10% cost
      adBudget: order.profit_snapshot?.adAmortization || (order.total_amount * 0.05) // Mock 5% cost
    });

    // 2. 动态成本分摊 (Marketing, Overhead)
    const allocatedCost = await this.allocateDynamicCosts(tenantId, orderId);
    snapshot.netProfit -= allocatedCost.total;
    snapshot.adAmortization += allocatedCost.marketing;

    // 重新计算 ROI 与利润率
    const costBasis = snapshot.purchasePrice + snapshot.logisticsCost;
    snapshot.roi = costBasis > 0 ? snapshot.netProfit / costBasis : 0;
    snapshot.profitRate = snapshot.sellingPrice > 0 ? snapshot.netProfit / snapshot.sellingPrice : 0;

    // 3. 持久化 P&L 快照
    await db(this.TABLE_NAME).insert({
      order_id: orderId,
      tenant_id: tenantId,
      selling_price: snapshot.sellingPrice,
      purchase_price: snapshot.purchasePrice,
      platform_fee: snapshot.platformFee,
      logistics_cost: snapshot.logisticsCost,
      tax: snapshot.tax,
      fx_hedging: snapshot.fxHedging,
      after_sales_loss: snapshot.afterSalesLoss,
      ad_amortization: snapshot.adAmortization,
      net_profit: snapshot.netProfit,
      roi: snapshot.roi,
      profit_rate: snapshot.profitRate,
      metadata: JSON.stringify(allocatedCost.details),
      created_at: new Date(),
      updated_at: new Date()
    }).onConflict('order_id').merge();

    logger.info(`[Settlement] P&L settled for Order ${orderId}. Net Profit: ${snapshot.netProfit}`);
    return snapshot;
  }

  /**
   * 动态成本分摊 (V30.0 BIZ_FIN_08)
   * 将营销、物流等动态成本分摊至订单级 P&L
   */
  private static async allocateDynamicCosts(tenantId: string, orderId: string): Promise<{
    total: number;
    marketing: number;
    details: any;
  }> {
    // 此处 Mock 简单逻辑：固定分摊
    const marketingAmortization = 0.50; // Mock $0.5
    const overheadAmortization = 0.20;  // Mock $0.2
    
    return {
      total: marketingAmortization + overheadAmortization,
      marketing: marketingAmortization,
      details: {
        marketing_amortization: marketingAmortization,
        overhead_amortization: overheadAmortization,
        method: 'PRO_RATA_BY_ORDER_COUNT'
      }
    };
  }

  /**
   * 获取租户结算汇总
   */
  static async getSettlementSummary(tenantId: string) {
    const summary = await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId })
      .select(
        db.raw('SUM(selling_price) as total_revenue'),
        db.raw('SUM(net_profit) as total_profit'),
        db.raw('AVG(roi) as avg_roi'),
        db.raw('AVG(profit_rate) as avg_profit_rate')
      )
      .first();

    return {
      totalRevenue: Number(summary?.total_revenue || 0),
      totalProfit: Number(summary?.total_profit || 0),
      avgROI: Number(summary?.avg_roi || 0),
      avgProfitRate: Number(summary?.avg_profit_rate || 0)
    };
  }
}
