import { IGetLeagueMembershipsPresenter, GetLeagueMembershipsResultDTO, GetLeagueMembershipsViewModel } from '@core/racing/application/presenters/IGetLeagueMembershipsPresenter';
import { LeagueMembershipsDTO } from '../dtos/LeagueMembershipsDTO';

export class GetLeagueMembershipsPresenter implements IGetLeagueMembershipsPresenter {
  private result: GetLeagueMembershipsViewModel | null = null;

  reset() {
    this.result = null;
  }

  present(dto: GetLeagueMembershipsResultDTO) {
    const driverMap = new Map(dto.drivers.map(d => [d.id, d]));
    const members = dto.memberships.map(membership => ({
      driverId: membership.driverId,
      driver: driverMap.get(membership.driverId)!,
      role: this.mapRole(membership.role) as 'owner' | 'manager' | 'member',
      joinedAt: membership.joinedAt,
    }));
    this.result = { memberships: { members } };
  }

  private mapRole(role: string): 'owner' | 'manager' | 'member' {
    switch (role) {
      case 'owner':
        return 'owner';
      case 'admin':
        return 'manager'; // Map admin to manager for API
      case 'steward':
        return 'member'; // Map steward to member for API
      case 'member':
        return 'member';
      default:
        return 'member';
    }
  }

  getViewModel(): GetLeagueMembershipsViewModel {
    if (!this.result) throw new Error('Presenter not presented');
    return this.result;
  }

  // API-specific method
  get apiViewModel(): LeagueMembershipsDTO | null {
    if (!this.result?.memberships) return null;
    return this.result.memberships as LeagueMembershipsViewModel;
  }
}