import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetLeagueStatsUseCase,
  type GetLeagueStatsInput,
  type GetLeagueStatsResult,
  type GetLeagueStatsErrorCode,
} from './GetLeagueStatsUseCase';
import { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetLeagueStatsUseCase', () => {
  let useCase: GetLeagueStatsUseCase;
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let raceRepository: {
    findByLeagueId: Mock;
  };
  let getDriverRating: Mock;
  let output: UseCaseOutputPort<GetLeagueStatsResult> & { present: Mock };

  beforeEach(() => {
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    raceRepository = {
      findByLeagueId: vi.fn(),
    };
    getDriverRating = vi.fn();
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetLeagueStatsResult> & { present: Mock };

    useCase = new GetLeagueStatsUseCase(
      leagueMembershipRepository as unknown as ILeagueMembershipRepository,
      raceRepository as unknown as IRaceRepository,
      getDriverRating,
      output,
    );
  });

  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);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);

    const presented = (output.present as Mock).mock.calls[0]?.[0] as GetLeagueStatsResult;

    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);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);

    const presented = (output.present as Mock).mock.calls[0]?.[0] as GetLeagueStatsResult;

    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');
    expect(output.present).not.toHaveBeenCalled();
  });

  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');
    expect(output.present).not.toHaveBeenCalled();
  });
});
