import type { UseCaseOutputPort } from '@core/shared/application';
import { GetLeagueMembershipsResult } from '@core/racing/application/use-cases/GetLeagueMembershipsUseCase';
import { LeagueMembershipsDTO } from '../dtos/LeagueMembershipsDTO';
import type { LeagueMemberDTO } from '../dtos/LeagueMemberDTO';

export interface GetLeagueMembershipsViewModel {
  memberships: LeagueMembershipsDTO;
}

export class GetLeagueMembershipsPresenter implements UseCaseOutputPort<GetLeagueMembershipsResult> {
  private result: GetLeagueMembershipsViewModel | null = null;

  reset() {
    this.result = null;
  }

  present(result: GetLeagueMembershipsResult) {
    const members: LeagueMemberDTO[] = result.memberships
      .filter(({ driver }) => driver !== null)
      .map(({ membership, driver }) => ({
        driverId: membership.driverId.toString(),
        driver: {
          id: driver!.id,
          iracingId: driver!.iracingId.toString(),
          name: driver!.name.toString(),
          country: driver!.country.toString(),
          joinedAt: driver!.joinedAt.toDate().toISOString(),
          ...(driver!.bio ? { bio: driver!.bio.toString() } : {}),
        },
        role: membership.role.toString() as 'owner' | 'admin' | 'steward' | 'member',
        joinedAt: membership.joinedAt.toDate().toISOString(),
      }));
    this.result = {
      memberships: {
        members,
      },
    };
  }

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