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

export interface LiquidityForecast {
  id?: string;
  tenant_id: string;
  node_id: string;
  forecast_date: Date;
  estimated_inflow: number;
  estimated_outflow: number;
  net_liquidity: number;
  risk_level: 'STABLE' | 'TIGHT' | 'CRITICAL';
  created_at?: Date;
}

/**
 * [BIZ_FIN_90] 跨主权多节点资金流动性自动预测 (Liquidity Forecast)
 * @description 基于历史清算数据，预测各 Hub 节点的资金缺口，自动建议资金调拨。
 */
export class NodeLiquidityForecastService {
  private static readonly FORECAST_TABLE = 'cf_node_liquidity_forecasts';

  /**
   * 执行节点流动性预测
   */
  static async forecastNodeLiquidity(tenantId: string, nodeId: string) {
    logger.info(`[LiquidityForecast] Forecasting liquidity for node: ${nodeId}`);

    // 1. 聚合历史清算数据 (联动 CrossNodeSettlementService)
    const history = await db('cf_cross_node_settlements')
      .where({ tenant_id: tenantId, target_node_id: nodeId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(db.raw('SUM(amount) as totalSettled'));

    const historicalAvg = Number(history[0].totalSettled || 0) / 30;

    // 2. AGI 预测 (简单模型：历史日均 * 1.2 系数)
    const estimatedInflow = historicalAvg * 0.8;
    const estimatedOutflow = historicalAvg * 1.1;
    const netLiquidity = estimatedInflow - estimatedOutflow;

    const riskLevel = netLiquidity < -1000 ? 'CRITICAL' : (netLiquidity < 0 ? 'TIGHT' : 'STABLE');

    const forecast: LiquidityForecast = {
      tenant_id: tenantId,
      node_id: nodeId,
      forecast_date: new Date(Date.now() + 24 * 60 * 60 * 1000), // 预测明天
      estimated_inflow: Number(estimatedInflow.toFixed(2)),
      estimated_outflow: Number(estimatedOutflow.toFixed(2)),
      net_liquidity: Number(netLiquidity.toFixed(2)),
      risk_level: riskLevel,
      created_at: new Date()
    };

    await db(this.FORECAST_TABLE).insert(forecast);

    if (riskLevel === 'CRITICAL') {
      logger.error(`[LiquidityForecast] CRITICAL liquidity risk for node ${nodeId}! Suggesting immediate rebalancing.`);
    }

    return forecast;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.FORECAST_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.FORECAST_TABLE} table...`);
      await db.schema.createTable(this.FORECAST_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('node_id', 128).notNullable().index();
        table.timestamp('forecast_date').notNullable();
        table.decimal('estimated_inflow', 15, 2);
        table.decimal('estimated_outflow', 15, 2);
        table.decimal('net_liquidity', 15, 2);
        table.string('risk_level', 16);
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
