import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { AsyncUseCase } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { GetLeagueMembershipsResultDTO } from '../dto/GetLeagueMembershipsResultDTO';

export interface GetLeagueMembershipsUseCaseParams {
  leagueId: string;
}

export class GetLeagueMembershipsUseCase implements AsyncUseCase<GetLeagueMembershipsUseCaseParams, GetLeagueMembershipsResultDTO, 'NO_ERROR'> {
  constructor(
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
    private readonly driverRepository: IDriverRepository,
  ) {}

  async execute(params: GetLeagueMembershipsUseCaseParams): Promise<Result<GetLeagueMembershipsResultDTO, ApplicationErrorCode<'NO_ERROR'>>> {
    const memberships = await this.leagueMembershipRepository.getLeagueMembers(params.leagueId);
    const drivers: { id: string; name: string }[] = [];

    // Get driver details for each membership
    for (const membership of memberships) {
      const driver = await this.driverRepository.findById(membership.driverId);
      if (driver) {
        drivers.push({ id: driver.id, name: driver.name });
      }
    }

    const dto: GetLeagueMembershipsResultDTO = {
      memberships,
      drivers,
    };
    return Result.ok(dto);
  }
}