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 { GetLeagueJoinRequestsResultDTO } from '../dto/GetLeagueJoinRequestsResultDTO';

export interface GetLeagueJoinRequestsUseCaseParams {
  leagueId: string;
}

export class GetLeagueJoinRequestsUseCase implements AsyncUseCase<GetLeagueJoinRequestsUseCaseParams, GetLeagueJoinRequestsResultDTO, 'NO_ERROR'> {
  constructor(
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
    private readonly driverRepository: IDriverRepository,
  ) {}

  async execute(params: GetLeagueJoinRequestsUseCaseParams): Promise<Result<GetLeagueJoinRequestsResultDTO, ApplicationErrorCode<'NO_ERROR'>>> {
    const joinRequests = await this.leagueMembershipRepository.getJoinRequests(params.leagueId);
    const driverIds = [...new Set(joinRequests.map(r => r.driverId))];
    const drivers = await Promise.all(driverIds.map(id => this.driverRepository.findById(id)));
    const driverMap = new Map(drivers.filter(d => d !== null).map(d => [d!.id, { id: d!.id, name: d!.name }]));
    const enrichedJoinRequests = joinRequests
      .filter(request => driverMap.has(request.driverId))
      .map(request => ({
        ...request,
        driver: driverMap.get(request.driverId)!,
      }));
    return Result.ok({
      joinRequests: enrichedJoinRequests,
    });
  }
}