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

export interface CashflowForecast {
  tenantId: string;
  period: string; // e.g., '2026-04'
  projectedInflow: number;
  projectedOutflow: number;
  netCashflow: number;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
  optimizationTips: string[];
}

/**
 * [BIZ_FIN_12] 实时现金流预测与资金调度 (Cashflow Forecasting)
 * @description 利用历史收支、待结货款、待付采购等数据，实时预测现金流并提供调度建议。
 */
export class CashflowForecastService {
  private static readonly TABLE_NAME = 'cf_cashflow_forecasts';

  /**
   * 初始化数据库表
   */
  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.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('period', 20).notNullable();
        table.decimal('projected_inflow', 15, 2);
        table.decimal('projected_outflow', 15, 2);
        table.decimal('net_cashflow', 15, 2);
        table.string('risk_level', 20);
        table.json('optimization_tips');
        table.timestamps(true, true);
        table.unique(['tenant_id', 'period']);
      });
    }
  }

  /**
   * 为租户生成下月现金流预测
   */
  static async generateForecast(tenantId: string, month: string): Promise<CashflowForecast> {
    // [BIZ_GOV_06] 功能开关校验
    if (!(await FeatureGovernanceService.isEnabled('BIZ_FIN_CASHFLOW', tenantId))) {
      logger.info(`[Finance] Cashflow forecast is disabled for Tenant ${tenantId}`);
      return { tenantId, period: month, projectedInflow: 0, projectedOutflow: 0, netCashflow: 0, riskLevel: 'LOW', optimizationTips: [] };
    }

    logger.info(`[Finance] Generating cashflow forecast for Tenant ${tenantId}, Month ${month}`);

    try {
      // 1. 获取待结订单金额 (Inflow)
      const pendingInflow = await db('cf_orders')
        .where({ tenant_id: tenantId, status: 'SHIPPED' }) // 已发货待回款
        .sum({ total: 'price' })
        .first();

      // 2. 获取待付采购金额 (Outflow)
      const pendingOutflow = await db('cf_purchase_orders')
        .where({ tenant_id: tenantId, status: 'PENDING_PAYMENT' })
        .sum({ total: 'total_cost' })
        .first();

      // 3. 计算预测值
      const projectedInflow = Number(pendingInflow?.total || 0) * 0.95; // 假设 5% 售后/退款风险
      const projectedOutflow = Number(pendingOutflow?.total || 0) + 1000; // 假设 1000 固定运营支出

      const netCashflow = projectedInflow - projectedOutflow;
      const riskLevel = netCashflow < 0 ? 'HIGH' : (netCashflow < 5000 ? 'MEDIUM' : 'LOW');

      const optimizationTips: string[] = [];
      if (netCashflow < 0) {
        optimizationTips.push('Speed up order fulfillment to reduce payout delay.');
        optimizationTips.push('Renegotiate payment terms with top suppliers.');
      } else if (netCashflow > 20000) {
        optimizationTips.push('Surplus cash detected. Consider reinvesting in high-ROI ad campaigns.');
      }

      const forecast: CashflowForecast = {
        tenantId,
        period: month,
        projectedInflow: Number(projectedInflow.toFixed(2)),
        projectedOutflow: Number(projectedOutflow.toFixed(2)),
        netCashflow: Number(netCashflow.toFixed(2)),
        riskLevel,
        optimizationTips
      };

      // 4. 保存到数据库
      await db(this.TABLE_NAME)
        .insert({
          tenant_id: tenantId,
          period: month,
          projected_inflow: forecast.projectedInflow,
          projected_outflow: forecast.projectedOutflow,
          net_cashflow: forecast.netCashflow,
          risk_level: riskLevel,
          optimization_tips: JSON.stringify(optimizationTips),
          created_at: new Date(),
          updated_at: new Date()
        })
        .onConflict(['tenant_id', 'period'])
        .merge();

      return forecast;
    } catch (err: any) {
      logger.error(`[Finance] Forecast failed: ${err.message}`);
      throw err;
    }
  }
}
