import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
import type { LeagueMembership } from '../../domain/entities/LeagueMembership';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';

export interface GetLeagueRosterMembersInput {
  leagueId: string;
}

export type GetLeagueRosterMembersErrorCode = 'LEAGUE_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface LeagueRosterMember {
  membership: LeagueMembership;
  driver: Driver;
}

export interface GetLeagueRosterMembersResult {
  members: LeagueRosterMember[];
}

export class GetLeagueRosterMembersUseCase {
  constructor(
    private readonly leagueMembershipRepository: LeagueMembershipRepository,
    private readonly driverRepository: DriverRepository,
    private readonly leagueRepository: LeagueRepository,
  ) {}

  async execute(
    input: GetLeagueRosterMembersInput,
  ): Promise<Result<GetLeagueRosterMembersResult, ApplicationErrorCode<GetLeagueRosterMembersErrorCode, { message: string }>>> {
    try {
      const leagueExists = await this.leagueRepository.exists(input.leagueId);

      if (!leagueExists) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

      const memberships = await this.leagueMembershipRepository.getLeagueMembers(input.leagueId);

      const driverIds = [...new Set(memberships.map(membership => membership.driverId.toString()))];
      const drivers = await Promise.all(driverIds.map(id => this.driverRepository.findById(id)));

      const driverMap = new Map<string, Driver>(
        drivers.filter((driver): driver is Driver => driver !== null).map(driver => [driver.id, driver]),
      );

      const members: LeagueRosterMember[] = memberships
        .filter(membership => driverMap.has(membership.driverId.toString()))
        .map(membership => ({
          membership,
          driver: driverMap.get(membership.driverId.toString())!,
        }));

      return Result.ok({ members });
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Failed to load league roster members';

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}