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

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 (team) => {
        const dto = new TeamListItemDTO();
        dto.id = team.id;
        dto.name = team.name;
        dto.tag = team.tag;
        dto.description = team.description || '';
        dto.memberCount = team.memberCount;
        dto.leagues = team.leagues || [];
        dto.totalWins = team.totalWins ?? 0;
        dto.totalRaces = team.totalRaces ?? 0;
        dto.performanceLevel = (team.performanceLevel as 'beginner' | 'intermediate' | 'advanced' | 'pro') ?? 'intermediate';
        dto.specialization = (team.specialization as 'endurance' | 'sprint' | 'mixed') ?? 'mixed';
        dto.region = team.region ?? '';
        dto.languages = team.languages ?? [];
        
        // Resolve logo URL using MediaResolverPort if available
        if (this.mediaResolver && team.logoRef) {
          const ref = team.logoRef instanceof MediaReference ? team.logoRef : MediaReference.fromJSON(team.logoRef);
          dto.logoUrl = await this.mediaResolver.resolve(ref);
        } else {
          // Fallback to existing logoUrl or null
          dto.logoUrl = team.logoUrl ?? null;
        }
        
        dto.rating = team.rating ?? 0;
        dto.category = team.category;
        dto.isRecruiting = team.isRecruiting;
        return dto;
      })
    );

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

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

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