import { Injectable } from '@nestjs/common';
import { LeaderboardScore } from '../value-objects';

export interface DirectTeamStats {
  referralId: bigint;
  teamCount: number;
}

/**
 * 龙虎榜计算领域服务
 *
 * 计算公式: 团队总认种量 - 最大单个直推团队认种量
 *
 * 设计目的:
 * - 鼓励均衡发展团队
 * - 防止\"烧伤\"现象（单腿发展）
 */
@Injectable()
export class LeaderboardCalculationService {
  /**
   * 计算龙虎榜分值
   */
  calculateScore(totalTeamCount: number, directTeamStats: DirectTeamStats[]): LeaderboardScore {
    const directTeamCounts = directTeamStats.map((s) => s.teamCount);
    return LeaderboardScore.calculate(totalTeamCount, directTeamCounts);
  }

  /**
   * 增量更新分值 (当有新认种时)
   * @param currentScore 当前分值
   * @param newPlantingCount 新增认种数量
   * @param fromDirectReferralId 来自哪个直推 (如果有)
   * @param directTeamStats 所有直推团队统计
   */
  updateScoreOnPlanting(
    currentScore: LeaderboardScore,
    newPlantingCount: number,
    fromDirectReferralId: bigint | undefined,
    directTeamStats: DirectTeamStats[],
  ): LeaderboardScore {
    // 更新直推团队统计
    const updatedStats = directTeamStats.map((s) => {
      if (fromDirectReferralId && s.referralId === fromDirectReferralId) {
        return { ...s, teamCount: s.teamCount + newPlantingCount };
      }
      return s;
    });

    const newTotalTeamCount = currentScore.totalTeamCount + newPlantingCount;
    return this.calculateScore(newTotalTeamCount, updatedStats);
  }

  /**
   * 比较两个用户的排名
   * @returns 负数表示a排在b前面, 正数表示b排在a前面
   */
  compareRank(scoreA: LeaderboardScore, scoreB: LeaderboardScore): number {
    return scoreA.compareTo(scoreB);
  }

  /**
   * 检查分值是否有效 (用于数据验证)
   */
  validateScore(score: LeaderboardScore, totalTeamCount: number, maxDirectTeamCount: number): boolean {
    const expectedScore = Math.max(0, totalTeamCount - maxDirectTeamCount);
    return score.score === expectedScore;
  }
}
