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

export interface FunnelMetrics {
  tenantId: string;
  sourceProducts: number; // 采集到的商品
  listedProducts: number; // 已刊登的商品
  activeOrders: number; // 活跃订单
  totalGMV: number; // 总成交额
  conversionRate: number; // 转化率
}

/**
 * [UX_START_02] 业务漏斗看板 (Business Funnel Dashboard)
 * @description 核心逻辑：提供业务导向的指标统计。
 * 针对业务初期商户，不展示“算力负载”或“ZKP 验证延迟”，而是展示“漏斗转化”：
 * 采集 -> 刊登 -> 出单 -> 利润。极大提升初期商户的业务成就感与目标感。
 */
export class BusinessFunnelService {
  /**
   * 获取租户实时业务漏斗指标
   */
  static async getFunnelMetrics(tenantId: string): Promise<FunnelMetrics> {
    logger.info(`[BusinessFunnel] Fetching funnel metrics for ${tenantId}`);

    try {
      // 1. 统计采集商品
      const sourceCount = await db('cf_product').where({ tenant_id: tenantId }).count('id as count');
      
      // 2. 统计已刊登商品 (模拟)
      const listedCount = await db('cf_product').where({ tenant_id: tenantId, status: 'ACTIVE' }).count('id as count');

      // 3. 统计订单与 GMV (模拟)
      const orders = await db('cf_orders').where({ tenant_id: tenantId }).select('total_amount');
      const orderCount = orders.length;
      const totalGMV = orders.reduce((sum, o) => sum + Number(o.total_amount), 0);

      // 4. 计算转化率
      const conversionRate = listedCount[0].count > 0 ? (orderCount / Number(listedCount[0].count)) * 100 : 0;

      return {
        tenantId,
        sourceProducts: Number(sourceCount[0].count),
        listedProducts: Number(listedCount[0].count),
        activeOrders: orderCount,
        totalGMV,
        conversionRate: Number(conversionRate.toFixed(2))
      };
    } catch (err: any) {
      logger.error(`[BusinessFunnel] Failed to fetch metrics: ${err.message}`);
      throw err;
    }
  }

  /**
   * 记录业务漏斗事件
   */
  static async recordFunnelEvent(tenantId: string, eventType: 'SOURCE' | 'LIST' | 'ORDER') {
    // 逻辑：异步触发指标刷新或实时聚合
    logger.debug(`[BusinessFunnel] Funnel event [${eventType}] recorded for ${tenantId}`);
  }
}
