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

/**
 * [BIZ_FIN_161] 订单级 P&L 实时穿透分析建议 (P&L)
 * @description 实时分析订单 P&L，剔除隐形成本。
 */
export class OrderProfitService {
  private static readonly PROFIT_TABLE = 'cf_order_profit_analysis';

  /**
   * 执行订单 P&L 分析
   */
  static async analyzeOrderProfit(tenantId: string, orderId: string) {
    logger.info(`[OrderProfit] Analyzing P&L for order: ${orderId} for tenant: ${tenantId}`);

    // 1. 获取基础对账数据
    const recon = await db('cf_recon_records').where({ orderId, tenantId }).first();
    if (!recon) return null;

    // 2. 获取隐形成本 (如摊销费用、手续费等)
    const expense = await db('cf_expense_amortizations').where({ tenantId }).orderBy('created_at', 'desc').first();
    const hiddenCost = expense ? expense.costPerOrder : 0;

    // 3. 计算真实净利
    const realNetProfit = recon.netProfit - hiddenCost;
    const realMargin = recon.platformAmount > 0 ? realNetProfit / recon.platformAmount : 0;

    const analysis = {
      id: `PA-${tenantId}-${orderId}`,
      tenantId,
      orderId,
      platformAmount: recon.platformAmount,
      baseNetProfit: recon.netProfit,
      hiddenCost: Number(hiddenCost.toFixed(4)),
      realNetProfit: Number(realNetProfit.toFixed(2)),
      realMargin: Number(realMargin.toFixed(4)),
      created_at: new Date()
    };

    // 4. 存储分析记录
    await db(this.PROFIT_TABLE)
      .insert(analysis)
      .onConflict(['id'])
      .merge();

    return analysis;
  }

  /**
   * 获取全局利润分解
   */
  static async getGlobalProfitBreakdown(tenantId: string) {
    logger.info(`[OrderProfit] Getting global profit breakdown for tenant: ${tenantId}`);

    const breakdown = await db(this.PROFIT_TABLE)
      .where({ tenantId })
      .select(
        db.raw('COUNT(*) as totalOrders'),
        db.raw('SUM(platformAmount) as totalPlatformAmount'),
        db.raw('SUM(baseNetProfit) as totalBaseNetProfit'),
        db.raw('SUM(hiddenCost) as totalHiddenCost'),
        db.raw('SUM(realNetProfit) as totalRealNetProfit'),
        db.raw('AVG(realMargin) as avgRealMargin')
      )
      .first();

    return breakdown || {
      totalOrders: 0,
      totalPlatformAmount: 0,
      totalBaseNetProfit: 0,
      totalHiddenCost: 0,
      totalRealNetProfit: 0,
      avgRealMargin: 0
    };
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.PROFIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.PROFIT_TABLE} table...`);
      await db.schema.createTable(this.PROFIT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.decimal('platformAmount', 15, 2);
        table.decimal('baseNetProfit', 15, 2);
        table.decimal('hiddenCost', 15, 4);
        table.decimal('realNetProfit', 15, 2);
        table.decimal('realMargin', 10, 4);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'orderId']);
      });
    }
  }
}
