import type { TeamRatingRepository } from '@core/racing/domain/repositories/TeamRatingRepository';
import type { TeamRepository } from '@core/racing/domain/repositories/TeamRepository';
import type { Logger } from '@core/shared/domain/Logger';

export interface TeamRanking {
  teamId: string;
  teamName: string;
  drivingRating: number;
  adminTrustRating: number;
  overallRating: number;
  eventCount: number;
  lastUpdated: Date;
  overallRank: number | null;
}

export class TeamRankingUseCase {
  constructor(
    private readonly ratingRepository: TeamRatingRepository,
    private readonly teamRepository: TeamRepository,
    private readonly logger: Logger,
  ) {}

  async getAllTeamRankings(): Promise<TeamRanking[]> {
    try {
      const teams = await this.teamRepository.findAll();
      const rankings: TeamRanking[] = [];

      for (const team of teams) {
        const snapshot = await this.ratingRepository.findByTeamId(team.id);
        if (snapshot) {
          rankings.push({
            teamId: team.id,
            teamName: team.name.toString(),
            drivingRating: snapshot.driving.value,
            adminTrustRating: snapshot.adminTrust.value,
            overallRating: snapshot.overall,
            eventCount: snapshot.eventCount,
            lastUpdated: snapshot.lastUpdated,
            overallRank: null,
          });
        }
      }

      // Sort by overall rating descending
      rankings.sort((a, b) => b.overallRating - a.overallRating);

      // Assign ranks
      return rankings.map((r, index) => ({
        ...r,
        overallRank: index + 1,
      }));
    } catch (error) {
      this.logger.error('Failed to get all team rankings', error as Error);
      throw error;
    }
  }

  async getTeamRanking(teamId: string): Promise<TeamRanking | null> {
    try {
      const team = await this.teamRepository.findById(teamId);
      if (!team) return null;

      const snapshot = await this.ratingRepository.findByTeamId(teamId);
      if (!snapshot) return null;

      const allRankings = await this.getAllTeamRankings();
      return allRankings.find(r => r.teamId === teamId) || null;
    } catch (error) {
      this.logger.error(`Failed to get team ranking for ${teamId}`, error as Error);
      throw error;
    }
  }
}
