import { Injectable } from '@nestjs/common';
import { DailyActiveStats } from '../aggregates/daily-active-stats/daily-active-stats.aggregate';
import { DauQueryResult } from '../repositories/event-log.repository.interface';

@Injectable()
export class DauCalculationService {
  /**
   * 从查询结果创建日活统计聚合
   */
  createStatsFromQueryResult(day: Date, result: DauQueryResult): DailyActiveStats {
    return DailyActiveStats.create({
      day,
      dauCount: result.total,
      dauByProvince: result.byProvince,
      dauByCity: result.byCity,
    });
  }

  /**
   * 合并多个查询结果（用于增量计算）
   */
  mergeQueryResults(results: DauQueryResult[]): DauQueryResult {
    const allIdentifiers = new Set<string>();
    const byProvince = new Map<string, Set<string>>();
    const byCity = new Map<string, Set<string>>();

    // 注意：这里简化处理，实际需要原始数据才能正确去重
    // 生产环境应该在数据库层面完成去重
    let total = 0;
    const provinceCount = new Map<string, number>();
    const cityCount = new Map<string, number>();

    for (const result of results) {
      total = Math.max(total, result.total);
      for (const [province, count] of result.byProvince) {
        provinceCount.set(province, Math.max(provinceCount.get(province) ?? 0, count));
      }
      for (const [city, count] of result.byCity) {
        cityCount.set(city, Math.max(cityCount.get(city) ?? 0, count));
      }
    }

    return {
      total,
      byProvince: provinceCount,
      byCity: cityCount,
    };
  }
}
