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

/**
 * [BIZ_FIN_168] 未来 30 天现金流枯竭预警模型 (Cashflow)
 * @description 联动库存、采购、销售，预警现金流枯竭风险。
 */
export class CashflowPredictor {
  private static readonly PREDICTION_TABLE = 'cf_cashflow_burn_alerts';

  /**
   * 预测现金流风险
   */
  static async predictCashflowBurn(tenantId: string) {
    logger.info(`[CashflowPredictor] Predicting burn for tenant: ${tenantId}`);

    // 1. 获取当前可用现金 (模拟从账户系统获取)
    const currentCash = 50000;

    // 2. 获取未来 30 天的待收回款 (SHIPPED 订单)
    const receivables = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, status: 'SHIPPED' })
      .select(db.raw('SUM(total_amount) as totalReceivables'));

    // 3. 获取未来 30 天的待付账单 (PENDING_PAYMENT PO)
    const payables = await db('cf_purchase_orders')
      .where({ tenant_id: tenantId, status: 'PENDING_PAYMENT' })
      .select(db.raw('SUM(total_amount) as totalPayables'));

    const totalReceivables = Number(receivables[0].totalReceivables || 0);
    const totalPayables = Number(payables[0].totalPayables || 0);

    // 4. 计算预计现金余额
    const projectedCash = currentCash + (totalReceivables * 0.8) - totalPayables; // 假设 80% 回款率

    let riskLevel = 'LOW';
    let alertMsg = 'Cashflow is healthy for next 30 days';

    if (projectedCash < 0) {
      riskLevel = 'CRITICAL';
      alertMsg = `Cashflow expected to be negative ($${projectedCash.toFixed(2)}) in 30 days. Secure financing!`;
    } else if (projectedCash < currentCash * 0.2) {
      riskLevel = 'WARNING';
      alertMsg = `Cash reserve dropping significantly ($${projectedCash.toFixed(2)}). Reduce expenses.`;
    }

    const prediction = {
      id: `CB-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      currentCash,
      totalReceivables,
      totalPayables,
      projectedCash: Number(projectedCash.toFixed(2)),
      riskLevel,
      alertMsg,
      created_at: new Date()
    };

    // 5. 存储预测记录
    await db(this.PREDICTION_TABLE)
      .insert(prediction)
      .onConflict(['id'])
      .merge();

    return prediction;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.PREDICTION_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.PREDICTION_TABLE} table...`);
      await db.schema.createTable(this.PREDICTION_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.decimal('currentCash', 15, 2);
        table.decimal('totalReceivables', 15, 2);
        table.decimal('totalPayables', 15, 2);
        table.decimal('projectedCash', 15, 2);
        table.string('riskLevel', 20); // E.g., LOW, WARNING, CRITICAL
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }
}
