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

/**
 * [BIZ_FIN_199] 全球多币种资产负债表实时快照 (Snapshot)
 * @description 实时生成多币种资产负债表快照，评估企业估值。
 */
export class GlobalBalanceSheet {
  private static readonly SNAPSHOT_TABLE = 'cf_global_balance_sheet_snapshots';

  /**
   * 生成资产负债表快照
   */
  static async generateSnapshot(tenantId: string) {
    logger.info(`[BalanceSheet] Generating snapshot for tenant: ${tenantId}`);

    // 1. 获取资产 (库存价值 + 待收回款)
    const inventoryValue = await db('cf_inventory')
      .where({ tenant_id: tenantId })
      .select(db.raw('SUM(quantity * cost_price) as totalInventoryValue'));

    const pendingPayouts = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, status: 'SHIPPED' }) // 假设已发货但未结算的订单为资产
      .select(db.raw('SUM(total_amount) as pendingPayouts'));

    const totalAssets = Number(inventoryValue[0].totalInventoryValue || 0) + Number(pendingPayouts[0].pendingPayouts || 0);

    // 2. 获取负债 (待付 PO)
    const pendingPOs = await db('cf_purchase_orders')
      .where({ tenant_id: tenantId, status: 'PENDING_PAYMENT' })
      .select(db.raw('SUM(total_amount) as pendingPOs'));

    const totalLiabilities = Number(pendingPOs[0].pendingPOs || 0);

    // 3. 计算净资产
    const netEquity = totalAssets - totalLiabilities;

    const snapshot = {
      id: `BS-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      totalAssets: Number(totalAssets.toFixed(2)),
      totalLiabilities: Number(totalLiabilities.toFixed(2)),
      netEquity: Number(netEquity.toFixed(2)),
      currency: 'USD',
      created_at: new Date()
    };

    // 4. 存储快照记录
    await db(this.SNAPSHOT_TABLE)
      .insert(snapshot)
      .onConflict(['id'])
      .merge();

    return snapshot;
  }

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