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

export interface HeatmapPoint {
  platform: string;
  riskLevel: string;
  count: number;
  avgProfitRate: number;
  avgROI: number;
}

/**
 * [UX_BI_05] 多维套利空间实时热力分析 (Arbitrage Heatmap)
 * @description 核心逻辑：对 cf_arbitrage_records 进行多维聚合，生成热力分析数据，支持前端可视化展示套利机会分布。
 */
export class ArbitrageHeatmapService {
  private static readonly TABLE_NAME = 'cf_arbitrage_records';

  /**
   * 获取租户套利热力图数据
   */
  static async getHeatmapData(tenantId: string): Promise<HeatmapPoint[]> {
    logger.info(`[ArbitrageHeatmap] Generating heatmap for Tenant: ${tenantId}`);

    try {
      // 聚合查询：按平台和风险等级分组
      const results = await db(this.TABLE_NAME)
        .where({ tenant_id: tenantId })
        .select(
          'target_platform as platform',
          'risk_level as riskLevel'
        )
        .count('id as count')
        .avg('initial_profit_rate as avgProfitRate')
        .avg('initial_roi as avgROI')
        .groupBy('target_platform', 'risk_level');

      return results.map(row => ({
        platform: row.platform,
        riskLevel: row.riskLevel,
        count: Number(row.count),
        avgProfitRate: Number(Number(row.avgProfitRate).toFixed(4)),
        avgROI: Number(Number(row.avgROI).toFixed(4))
      }));
    } catch (err: any) {
      logger.error(`[ArbitrageHeatmap] Failed to aggregate heatmap: ${err.message}`);
      throw err;
    }
  }

  /**
   * 获取趋势热力分析 (按时间维度聚合)
   */
  static async getTrendHeatmap(tenantId: string, days: number = 7) {
    logger.info(`[ArbitrageHeatmap] Generating trend heatmap for Tenant: ${tenantId}, past ${days} days`);

    try {
      const results = await db(this.TABLE_NAME)
        .where({ tenant_id: tenantId })
        .andWhere('created_at', '>=', db.raw('DATE_SUB(NOW(), INTERVAL ? DAY)', [days]))
        .select(
          db.raw('DATE(created_at) as date'),
          'target_platform as platform'
        )
        .count('id as count')
        .avg('initial_roi as avgROI')
        .groupBy('date', 'target_platform')
        .orderBy('date', 'desc');

      return results;
    } catch (err: any) {
      logger.error(`[ArbitrageHeatmap] Failed to aggregate trend: ${err.message}`);
      throw err;
    }
  }
}
