import { RaceResultsDetailDto, RaceResultDto } from '../dtos';
import { RaceResultViewModel } from './RaceResultViewModel';

export class RaceResultsDetailViewModel implements RaceResultsDetailDto {
  raceId: string;
  track: string;
  results: RaceResultViewModel[];
  league?: { id: string; name: string };
  race?: { id: string; track: string; scheduledAt: string };
  drivers: { id: string; name: string }[];
  pointsSystem: Record<number, number>;
  fastestLapTime: number;
  penalties: { driverId: string; type: string; value?: number }[];
  currentDriverId: string;

  private currentUserId: string;

  constructor(dto: RaceResultsDetailDto & { results: RaceResultDto[] }, currentUserId: string) {
    this.raceId = dto.raceId;
    this.track = dto.track;
    this.results = dto.results.map(r => new RaceResultViewModel({ ...r, raceId: dto.raceId }));
    this.league = dto.league;
    this.race = dto.race;
    this.drivers = dto.drivers;
    this.pointsSystem = dto.pointsSystem;
    this.fastestLapTime = dto.fastestLapTime;
    this.penalties = dto.penalties;
    this.currentDriverId = dto.currentDriverId;
    this.currentUserId = currentUserId;
  }

  /** UI-specific: Results sorted by position */
  get resultsByPosition(): RaceResultViewModel[] {
    return [...this.results].sort((a, b) => a.position - b.position);
  }

  /** UI-specific: Results sorted by fastest lap */
  get resultsByFastestLap(): RaceResultViewModel[] {
    return [...this.results].sort((a, b) => a.fastestLap - b.fastestLap);
  }

  /** UI-specific: Clean drivers only */
  get cleanDrivers(): RaceResultViewModel[] {
    return this.results.filter(r => r.isClean);
  }

  /** UI-specific: Current user's result */
  get currentUserResult(): RaceResultViewModel | undefined {
    return this.results.find(r => r.driverId === this.currentUserId);
  }

  /** UI-specific: Race stats */
  get stats(): { totalDrivers: number; cleanRate: number; averageIncidents: number } {
    const total = this.results.length;
    const clean = this.cleanDrivers.length;
    const totalIncidents = this.results.reduce((sum, r) => sum + r.incidents, 0);
    return {
      totalDrivers: total,
      cleanRate: total > 0 ? (clean / total) * 100 : 0,
      averageIncidents: total > 0 ? totalIncidents / total : 0
    };
  }
}