import { MediaReference } from '@core/domain/media/MediaReference';
import type { MediaResolverPort } from '@core/ports/media/MediaResolverPort';
import type {
    GetDriversLeaderboardResult,
} from '@core/racing/application/use-cases/GetDriversLeaderboardUseCase';
import { DriversLeaderboardDTO } from '../dtos/DriversLeaderboardDTO';

export class DriversLeaderboardPresenter {
  private responseModel: DriversLeaderboardDTO | null = null;
  private mediaResolver?: MediaResolverPort;

  setMediaResolver(resolver: MediaResolverPort): void {
    this.mediaResolver = resolver;
  }

  async present(data: GetDriversLeaderboardResult): Promise<void> {
    const drivers = await Promise.all(
      data.items.map(async (item) => {
        // Resolve avatar URL using MediaResolverPort if available
        let avatarUrl: string | null = null;
        if (this.mediaResolver && item.avatarRef) {
          const ref = item.avatarRef instanceof MediaReference ? item.avatarRef : MediaReference.fromJSON(item.avatarRef);
          const resolvedUrl = await this.mediaResolver.resolve(ref);
          if (resolvedUrl) {
            avatarUrl = resolvedUrl;
          }
        }

        return {
          id: item.driver.id,
          name: item.driver.name.toString(),
          rating: item.rating,
          skillLevel: item.skillLevel,
          ...(item.driver.category !== undefined ? { category: item.driver.category } : {}),
          nationality: item.driver.country.toString(),
          racesCompleted: item.racesCompleted,
          wins: item.wins,
          podiums: item.podiums,
          isActive: item.isActive,
          rank: item.rank,
          avatarUrl,
        };
      })
    );

    this.responseModel = {
      drivers,
      totalRaces: data.totalRaces,
      totalWins: data.totalWins,
      activeCount: data.activeCount,
    };
  }

  getResponseModel(): DriversLeaderboardDTO {
    if (!this.responseModel) throw new Error('Presenter not presented');
    return this.responseModel;
  }
}