import { RaceStewardingViewData, Protest, Penalty, Driver } from '@/lib/view-data/races/RaceStewardingViewData';

/**
 * Race Stewarding View Data Builder
 * 
 * Transforms API DTO into ViewData for the race stewarding template.
 * Deterministic, side-effect free.
 */
export class RaceStewardingViewDataBuilder {
  static build(apiDto: unknown): RaceStewardingViewData {
    if (!apiDto) {
      return {
        race: null,
        league: null,
        pendingProtests: [],
        resolvedProtests: [],
        penalties: [],
        driverMap: {},
        pendingCount: 0,
        resolvedCount: 0,
        penaltiesCount: 0,
      };
    }

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

    const race = dto.race ? {
      id: dto.race.id,
      track: dto.race.track,
      scheduledAt: dto.race.scheduledAt,
    } : null;

    const league = dto.league ? {
      id: dto.league.id,
    } : null;

    const pendingProtests: Protest[] = (dto.pendingProtests || []).map((p: any) => ({
      id: p.id,
      protestingDriverId: p.protestingDriverId,
      accusedDriverId: p.accusedDriverId,
      incident: {
        lap: p.incident?.lap || 0,
        description: p.incident?.description || '',
      },
      filedAt: p.filedAt,
      status: p.status,
      proofVideoUrl: p.proofVideoUrl,
      decisionNotes: p.decisionNotes,
    }));

    const resolvedProtests: Protest[] = (dto.resolvedProtests || []).map((p: any) => ({
      id: p.id,
      protestingDriverId: p.protestingDriverId,
      accusedDriverId: p.accusedDriverId,
      incident: {
        lap: p.incident?.lap || 0,
        description: p.incident?.description || '',
      },
      filedAt: p.filedAt,
      status: p.status,
      proofVideoUrl: p.proofVideoUrl,
      decisionNotes: p.decisionNotes,
    }));

    const penalties: Penalty[] = (dto.penalties || []).map((p: any) => ({
      id: p.id,
      driverId: p.driverId,
      type: p.type,
      value: p.value || 0,
      reason: p.reason || '',
      notes: p.notes,
    }));

    const driverMap: Record<string, Driver> = dto.driverMap || {};

    return {
      race,
      league,
      pendingProtests,
      resolvedProtests,
      penalties,
      driverMap,
      pendingCount: dto.pendingCount || pendingProtests.length,
      resolvedCount: dto.resolvedCount || resolvedProtests.length,
      penaltiesCount: dto.penaltiesCount || penalties.length,
    };
  }
}