import type { UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/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 { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';

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: ILeagueMembershipRepository,
    private readonly driverRepository: IDriverRepository,
    private readonly leagueRepository: ILeagueRepository,
    private readonly output: UseCaseOutputPort<GetLeagueRosterMembersResult>,
  ) {}

  async execute(
    input: GetLeagueRosterMembersInput,
  ): Promise<Result<void, 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())!,
        }));

      this.output.present({ members });

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

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