import type {
  IRaceProtestsPresenter,
  RaceProtestViewModel,
  RaceProtestsResultDTO,
  RaceProtestsViewModel,
} from '@core/racing/application/presenters/IRaceProtestsPresenter';

export class RaceProtestsPresenter implements IRaceProtestsPresenter {
  private viewModel: RaceProtestsViewModel | null = null;

  reset(): void {
    this.viewModel = null;
  }

  present(dto: RaceProtestsResultDTO): void {
    const { protests, driverMap } = dto;

    const protestViewModels: RaceProtestViewModel[] = protests.map((protest) => {
      const base: RaceProtestViewModel = {
        id: protest.id,
        raceId: protest.raceId,
        protestingDriverId: protest.protestingDriverId,
        protestingDriverName: driverMap.get(protest.protestingDriverId) || 'Unknown',
        accusedDriverId: protest.accusedDriverId,
        accusedDriverName: driverMap.get(protest.accusedDriverId) || 'Unknown',
        incident: protest.incident,
        filedAt: protest.filedAt.toISOString(),
        status: protest.status,
      };

      const comment = protest.comment;
      const proofVideoUrl = protest.proofVideoUrl;
      const reviewedBy = protest.reviewedBy;
      const reviewedByName =
        protest.reviewedBy !== undefined
          ? driverMap.get(protest.reviewedBy) ?? 'Unknown'
          : undefined;
      const decisionNotes = protest.decisionNotes;
      const reviewedAt = protest.reviewedAt?.toISOString();

      return {
        ...base,
        ...(comment !== undefined ? { comment } : {}),
        ...(proofVideoUrl !== undefined ? { proofVideoUrl } : {}),
        ...(reviewedBy !== undefined ? { reviewedBy } : {}),
        ...(reviewedByName !== undefined ? { reviewedByName } : {}),
        ...(decisionNotes !== undefined ? { decisionNotes } : {}),
        ...(reviewedAt !== undefined ? { reviewedAt } : {}),
      };
    });

    this.viewModel = {
      protests: protestViewModels,
    };
  }

  getViewModel(): RaceProtestsViewModel | null {
    return this.viewModel;
  }
}