import {
  ITeamMembersPresenter,
  TeamMembersResultDTO,
  TeamMembersViewModel,
  TeamMemberViewModel,
} from '@core/racing/application/presenters/ITeamMembersPresenter';

export class TeamMembersPresenter implements ITeamMembersPresenter {
  private result: TeamMembersViewModel | null = null;

  reset() {
    this.result = null;
  }

  present(dto: TeamMembersResultDTO) {
    const { memberships, driverNames, avatarUrls } = dto;

    const members: TeamMemberViewModel[] = memberships.map((membership) => ({
      driverId: membership.driverId,
      driverName: driverNames[membership.driverId] || 'Unknown',
      role: membership.role as 'owner' | 'manager' | 'member',
      joinedAt: membership.joinedAt.toISOString(),
      isActive: membership.status === 'active',
      avatarUrl: avatarUrls[membership.driverId] || '',
    }));

    const ownerCount = members.filter((m) => m.role === 'owner').length;
    const managerCount = members.filter((m) => m.role === 'manager').length;
    const memberCount = members.filter((m) => m.role === 'member').length;

    this.result = {
      members,
      totalCount: members.length,
      ownerCount,
      managerCount,
      memberCount,
    };
  }

  getViewModel(): TeamMembersViewModel | null {
    return this.result;
  }

  get viewModel(): TeamMembersViewModel {
    if (!this.result) throw new Error('Presenter not presented');
    return this.result;
  }
}