import { MediaReference } from '@core/domain/media/MediaReference';
import type { MediaResolverPort } from '@core/ports/media/MediaResolverPort';
import type { GetAllTeamsResult } from '@core/racing/application/use-cases/GetAllTeamsUseCase';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import { GetAllTeamsOutputDTO } from '../dtos/GetAllTeamsOutputDTO';
import { TeamListItemDTO } from '../dtos/TeamListItemDTO';

export class AllTeamsPresenter implements UseCaseOutputPort<GetAllTeamsResult> {
  private model: GetAllTeamsOutputDTO | null = null;
  private mediaResolver?: MediaResolverPort;

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

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

  async present(result: GetAllTeamsResult): Promise<void> {
    const teams: TeamListItemDTO[] = await Promise.all(
      result.teams.map(async (enrichedTeam) => {
        const dto = new TeamListItemDTO();
        dto.id = enrichedTeam.team.id;
        dto.name = enrichedTeam.team.name.toString();
        dto.tag = enrichedTeam.team.tag.toString();
        dto.description = enrichedTeam.team.description.toString() || '';
        dto.memberCount = enrichedTeam.memberCount;
        dto.leagues = enrichedTeam.team.leagues.map(l => l.toString()) || [];
        dto.totalWins = enrichedTeam.totalWins;
        dto.totalRaces = enrichedTeam.totalRaces;
        dto.performanceLevel = enrichedTeam.performanceLevel;
        dto.specialization = enrichedTeam.specialization;
        dto.region = enrichedTeam.region;
        dto.languages = enrichedTeam.languages;
        
        // Resolve logo URL using MediaResolverPort if available
        if (this.mediaResolver && enrichedTeam.team.logoRef) {
          const ref = enrichedTeam.team.logoRef instanceof MediaReference ? enrichedTeam.team.logoRef : MediaReference.fromJSON(enrichedTeam.team.logoRef);
          dto.logoUrl = await this.mediaResolver.resolve(ref);
        } else {
          // Fallback to enriched logoUrl or null
          dto.logoUrl = enrichedTeam.logoUrl;
        }
        
        dto.rating = enrichedTeam.rating;
        dto.category = enrichedTeam.team.category;
        dto.isRecruiting = enrichedTeam.team.isRecruiting;
        return dto;
      })
    );

    this.model = {
      teams,
      totalCount: result.totalCount,
    };
  }

  getResponseModel(): GetAllTeamsOutputDTO | null {
    return this.model;
  }

  get responseModel(): GetAllTeamsOutputDTO {
    if (!this.model) throw new Error('Presenter not presented');
    return this.model;
  }
}