import { RaceResultsViewData, RaceResultsResult, RaceResultsPenalty } from '@/lib/view-data/races/RaceResultsViewData';

/**
 * Race Results View Data Builder
 * 
 * Transforms API DTO into ViewData for the race results template.
 * Deterministic, side-effect free.
 */
export class RaceResultsViewDataBuilder {
  static build(apiDto: unknown): RaceResultsViewData {
    if (!apiDto) {
      return {
        raceSOF: null,
        results: [],
        penalties: [],
        pointsSystem: {},
        fastestLapTime: 0,
      };
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const dto = apiDto as any;

    // Transform results
    const results: RaceResultsResult[] = (dto.results || []).map((result: any) => ({
      position: result.position,
      driverId: result.driverId,
      driverName: result.driverName,
      driverAvatar: result.avatarUrl,
      country: result.country || 'US',
      car: result.car || 'Unknown',
      laps: result.laps || 0,
      time: result.time || '0:00.00',
      fastestLap: result.fastestLap?.toString() || '0.00',
      points: result.points || 0,
      incidents: result.incidents || 0,
      isCurrentUser: result.isCurrentUser || false,
    }));

    // Transform penalties
    const penalties: RaceResultsPenalty[] = (dto.penalties || []).map((penalty: any) => ({
      driverId: penalty.driverId,
      driverName: penalty.driverName || 'Unknown',
      type: penalty.type as 'time_penalty' | 'grid_penalty' | 'points_deduction' | 'disqualification' | 'warning' | 'license_points',
      value: penalty.value || 0,
      reason: penalty.reason || 'Penalty applied',
      notes: penalty.notes,
    }));

    return {
      raceTrack: dto.race?.track,
      raceScheduledAt: dto.race?.scheduledAt,
      totalDrivers: dto.stats?.totalDrivers,
      leagueName: dto.league?.name,
      raceSOF: dto.strengthOfField || null,
      results,
      penalties,
      pointsSystem: dto.pointsSystem || {},
      fastestLapTime: dto.fastestLapTime || 0,
    };
  }
}