import type {
  ILeagueStatsPresenter,
  LeagueStatsViewModel,
} from '@core/racing/application/presenters/ILeagueStatsPresenter';

export class LeagueStatsPresenter implements ILeagueStatsPresenter {
  private viewModel: LeagueStatsViewModel | null = null;

  present(
    leagueId: string,
    totalRaces: number,
    completedRaces: number,
    scheduledRaces: number,
    sofValues: number[]
  ): LeagueStatsViewModel {
    const averageSOF = sofValues.length > 0
      ? Math.round(sofValues.reduce((a, b) => a + b, 0) / sofValues.length)
      : null;
    
    const highestSOF = sofValues.length > 0 ? Math.max(...sofValues) : null;
    const lowestSOF = sofValues.length > 0 ? Math.min(...sofValues) : null;

    this.viewModel = {
      leagueId,
      totalRaces,
      completedRaces,
      scheduledRaces,
      averageSOF,
      highestSOF,
      lowestSOF,
    };

    return this.viewModel;
  }

  getViewModel(): LeagueStatsViewModel {
    if (!this.viewModel) {
      throw new Error('Presenter has not been called yet');
    }
    return this.viewModel;
  }
}