import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
import type { League } from '../../domain/entities/League';
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 GetLeagueMembershipsInput {
  leagueId: string;
}

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

export interface LeagueMembershipWithDriver {
  membership: LeagueMembership;
  driver: Driver | null;
}

export interface GetLeagueMembershipsResult {
  league: League;
  memberships: LeagueMembershipWithDriver[];
}

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

  async execute(
    input: GetLeagueMembershipsInput,
  ): Promise<Result<GetLeagueMembershipsResult, ApplicationErrorCode<GetLeagueMembershipsErrorCode, { message: string }>>> {
    try {
      const league = await this.leagueRepository.findById(input.leagueId);

      if (!league) {
        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 membershipsWithDrivers: LeagueMembershipWithDriver[] = memberships.map(membership => ({
        membership,
        driver: driverMap.get(membership.driverId.toString()) ?? null,
      }));

      const result: GetLeagueMembershipsResult = {
        league,
        memberships: membershipsWithDrivers,
      };

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

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