import { RaceDetailViewData, RaceDetailRace, RaceDetailLeague, RaceDetailEntry, RaceDetailRegistration, RaceDetailUserResult } from '@/lib/view-data/races/RaceDetailViewData';

/**
 * Race Detail View Data Builder
 * 
 * Transforms API DTO into ViewData for the race detail template.
 * Deterministic, side-effect free.
 */
export class RaceDetailViewDataBuilder {
  static build(apiDto: any): RaceDetailViewData {
    if (!apiDto || !apiDto.race) {
      return {
        race: {
          id: '',
          track: '',
          car: '',
          scheduledAt: '',
          status: 'scheduled',
          sessionType: 'race',
        },
        entryList: [],
        registration: {
          isUserRegistered: false,
          canRegister: false,
        },
        canReopenRace: false,
      };
    }

    const race: RaceDetailRace = {
      id: apiDto.race.id,
      track: apiDto.race.track,
      car: apiDto.race.car,
      scheduledAt: apiDto.race.scheduledAt,
      status: apiDto.race.status as 'scheduled' | 'running' | 'completed' | 'cancelled',
      sessionType: apiDto.race.sessionType,
    };

    const league: RaceDetailLeague | undefined = apiDto.league ? {
      id: apiDto.league.id,
      name: apiDto.league.name,
      description: apiDto.league.description || undefined,
      settings: {
        maxDrivers: apiDto.league.settings?.maxDrivers || 32,
        qualifyingFormat: apiDto.league.settings?.qualifyingFormat || 'Open',
      },
    } : undefined;

    const entryList: RaceDetailEntry[] = apiDto.entryList.map((entry: any) => ({
      id: entry.id,
      name: entry.name,
      avatarUrl: entry.avatarUrl,
      country: entry.country,
      rating: entry.rating,
      isCurrentUser: entry.isCurrentUser,
    }));

    const registration: RaceDetailRegistration = {
      isUserRegistered: apiDto.registration.isUserRegistered,
      canRegister: apiDto.registration.canRegister,
    };

    const userResult: RaceDetailUserResult | undefined = apiDto.userResult ? {
      position: apiDto.userResult.position,
      startPosition: apiDto.userResult.startPosition,
      positionChange: apiDto.userResult.positionChange,
      incidents: apiDto.userResult.incidents,
      isClean: apiDto.userResult.isClean,
      isPodium: apiDto.userResult.isPodium,
      ratingChange: apiDto.userResult.ratingChange,
    } : undefined;

    return {
      race,
      league,
      entryList,
      registration,
      userResult,
      canReopenRace: apiDto.canReopenRace || false,
    };
  }
}