import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import {
    GetLeagueStatsUseCase,
    type GetLeagueStatsErrorCode,
    type GetLeagueStatsInput,
} from './GetLeagueStatsUseCase';

describe('GetLeagueStatsUseCase', () => {
  let useCase: GetLeagueStatsUseCase;
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let raceRepository: {
    findByLeagueId: Mock;
  };
  let getDriverRating: Mock;

  beforeEach(() => {
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    raceRepository = {
      findByLeagueId: vi.fn(),
    };
    getDriverRating = vi.fn();
    useCase = new GetLeagueStatsUseCase(leagueMembershipRepository as unknown as LeagueMembershipRepository,
      raceRepository as unknown as RaceRepository,
      getDriverRating);
  });

  it('should return league stats with average rating', async () => {
    const input: GetLeagueStatsInput = { leagueId: 'league-1' };
    const memberships = [
      { driverId: 'driver-1' },
      { driverId: 'driver-2' },
      { driverId: 'driver-3' },
    ];
    const races = [{ id: 'race-1' }, { id: 'race-2' }];

    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    raceRepository.findByLeagueId.mockResolvedValue(races);
    getDriverRating.mockImplementation((driverInput: { driverId: string }) => {
      if (driverInput.driverId === 'driver-1') return Promise.resolve({ rating: 1500, ratingChange: null });
      if (driverInput.driverId === 'driver-2') return Promise.resolve({ rating: 1600, ratingChange: null });
      if (driverInput.driverId === 'driver-3') return Promise.resolve({ rating: null, ratingChange: null });
      return Promise.resolve({ rating: null, ratingChange: null });
    });

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();
    expect(presented.leagueId).toBe(input.leagueId);
    expect(presented.driverCount).toBe(3);
    expect(presented.raceCount).toBe(2);
    expect(presented.averageRating).toBe(1550); // (1500 + 1600) / 2
  });

  it('should return 0 average rating when no valid ratings', async () => {
    const input: GetLeagueStatsInput = { leagueId: 'league-1' };
    const memberships = [{ driverId: 'driver-1' }];
    const races = [{ id: 'race-1' }];

    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    raceRepository.findByLeagueId.mockResolvedValue(races);
    getDriverRating.mockResolvedValue({ rating: null, ratingChange: null });

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();
    expect(presented.leagueId).toBe(input.leagueId);
    expect(presented.driverCount).toBe(1);
    expect(presented.raceCount).toBe(1);
    expect(presented.averageRating).toBe(0);
  });

  it('should return error when league has no members', async () => {
    const input: GetLeagueStatsInput = { leagueId: 'league-1' };

    leagueMembershipRepository.getLeagueMembers.mockResolvedValue([]);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueStatsErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('LEAGUE_NOT_FOUND');
    expect(error.details.message).toBe('League not found');
  });

  it('should return error when repository fails', async () => {
    const input: GetLeagueStatsInput = { leagueId: 'league-1' };
    leagueMembershipRepository.getLeagueMembers.mockRejectedValue(new Error('DB error'));

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueStatsErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details.message).toBe('DB error');
  });
});
