import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';

export interface GetLeagueStatsInput {
  leagueId: string;
}

export interface GetLeagueStatsResult {
  leagueId: string;
  driverCount: number;
  raceCount: number;
  averageRating: number;
}

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

export class GetLeagueStatsUseCase {
  constructor(
    private readonly leagueMembershipRepository: LeagueMembershipRepository,
    private readonly raceRepository: RaceRepository,
    private readonly getDriverRating: (input: {
      driverId: string;
    }) => Promise<{ rating: number | null; ratingChange: number | null }>,
  ) {}

  async execute(
    input: GetLeagueStatsInput,
  ): Promise<Result<GetLeagueStatsResult, ApplicationErrorCode<GetLeagueStatsErrorCode, { message: string }>>> {
    try {
      const memberships = await this.leagueMembershipRepository.getLeagueMembers(input.leagueId);

      if (memberships.length === 0) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

      const races = await this.raceRepository.findByLeagueId(input.leagueId);
      const driverIds = memberships.map(membership => String(membership.driverId));

      const ratingPromises = driverIds.map(driverId => this.getDriverRating({ driverId }));

      const ratingResults = await Promise.all(ratingPromises);
      const validRatings = ratingResults
        .map(result => result.rating)
        .filter((rating): rating is number => rating !== null);

      const averageRating =
        validRatings.length > 0
          ? Math.round(validRatings.reduce((sum, rating) => sum + rating, 0) / validRatings.length)
          : 0;

      const result: GetLeagueStatsResult = {
        leagueId: input.leagueId,
        driverCount: memberships.length,
        raceCount: races.length,
        averageRating,
      };

      return Result.ok(result);
    } catch (error) {
      const message =
        error instanceof Error && error.message ? error.message : 'Failed to fetch league stats';

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