import { DriversLeaderboardDTO, DriverLeaderboardItemDTO } from '../dtos/DriversLeaderboardDTO';
import { DriverLeaderboardItemDTO } from '../dtos/DriverLeaderboardItemDTO';
import type { IDriversLeaderboardPresenter, DriversLeaderboardResultDTO } from '../../../../../core/racing/application/presenters/IDriversLeaderboardPresenter';

export class DriversLeaderboardPresenter implements IDriversLeaderboardPresenter {
  private result: DriversLeaderboardDTO | null = null;

  reset() {
    this.result = null;
  }

  present(dto: DriversLeaderboardResultDTO) {
    const drivers: DriverLeaderboardItemDTO[] = dto.drivers.map(driver => {
      const ranking = dto.rankings.find(r => r.driverId === driver.id);
      const stats = dto.stats[driver.id];
      const avatarUrl = dto.avatarUrls[driver.id];

      return {
        id: driver.id,
        name: driver.name,
        rating: ranking?.rating ?? 0,
        skillLevel: 'Pro', // TODO: map from domain
        nationality: driver.country,
        racesCompleted: stats?.racesCompleted ?? 0,
        wins: stats?.wins ?? 0,
        podiums: stats?.podiums ?? 0,
        isActive: true, // TODO: determine from domain
        rank: ranking?.overallRank ?? 0,
        avatarUrl,
      };
    });

    // Calculate totals
    const totalRaces = drivers.reduce((sum, d) => sum + (d.racesCompleted ?? 0), 0);
    const totalWins = drivers.reduce((sum, d) => sum + (d.wins ?? 0), 0);
    const activeCount = drivers.filter(d => d.isActive).length;

    this.result = {
      drivers: drivers.sort((a, b) => (b.rating ?? 0) - (a.rating ?? 0)),
      totalRaces,
      totalWins,
      activeCount,
    };
  }

  get viewModel(): DriversLeaderboardDTO {
    if (!this.result) throw new Error('Presenter not presented');
    return this.result;
  }
}