import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { GetRaceWithSOFUseCase } from './GetRaceWithSOFUseCase';
import { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import { IRaceRegistrationRepository } from '../../domain/repositories/IRaceRegistrationRepository';
import { IResultRepository } from '../../domain/repositories/IResultRepository';
import { DriverRatingProvider } from '../ports/DriverRatingProvider';
import { Race } from '../../domain/entities/Race';
import { SessionType } from '../../domain/value-objects/SessionType';

describe('GetRaceWithSOFUseCase', () => {
  let useCase: GetRaceWithSOFUseCase;
  let raceRepository: {
    findById: Mock;
  };
  let registrationRepository: {
    getRegisteredDrivers: Mock;
  };
  let resultRepository: {
    findByRaceId: Mock;
  };
  let driverRatingProvider: {
    getRatings: Mock;
  };

  beforeEach(() => {
    raceRepository = {
      findById: vi.fn(),
    };
    registrationRepository = {
      getRegisteredDrivers: vi.fn(),
    };
    resultRepository = {
      findByRaceId: vi.fn(),
    };
    driverRatingProvider = {
      getRatings: vi.fn(),
    };
    useCase = new GetRaceWithSOFUseCase(
      raceRepository as unknown as IRaceRepository,
      registrationRepository as unknown as IRaceRegistrationRepository,
      resultRepository as unknown as IResultRepository,
      driverRatingProvider as unknown as DriverRatingProvider,
    );
  });

  it('should return error when race not found', async () => {
    raceRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({ code: 'RACE_NOT_FOUND' });
  });

  it('should return race with stored SOF when available', async () => {
    const race = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      scheduledAt: new Date(),
      track: 'Track 1',
      car: 'Car 1',
      sessionType: SessionType.main(),
      status: 'scheduled',
      strengthOfField: 1500,
      registeredCount: 10,
      maxParticipants: 20,
    });

    raceRepository.findById.mockResolvedValue(race);
    registrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1', 'driver-2', 'driver-3', 'driver-4', 'driver-5', 'driver-6', 'driver-7', 'driver-8', 'driver-9', 'driver-10']);

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.raceId).toBe('race-1');
    expect(dto.leagueId).toBe('league-1');
    expect(dto.strengthOfField).toBe(1500);
    expect(dto.registeredCount).toBe(10);
    expect(dto.maxParticipants).toBe(20);
    expect(dto.participantCount).toBe(10);
    expect(dto.sessionType).toBe('main');
    expect(dto.status).toBe('scheduled');
  });

  it('should calculate SOF for upcoming race using registrations', async () => {
    const race = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      scheduledAt: new Date(),
      track: 'Track 1',
      car: 'Car 1',
      sessionType: SessionType.main(),
      status: 'scheduled',
    });

    raceRepository.findById.mockResolvedValue(race);
    registrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1', 'driver-2']);
    driverRatingProvider.getRatings.mockReturnValue(new Map([
      ['driver-1', 1400],
      ['driver-2', 1600],
    ]));

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.strengthOfField).toBe(1500); // average
    expect(dto.participantCount).toBe(2);
    expect(registrationRepository.getRegisteredDrivers).toHaveBeenCalledWith('race-1');
    expect(resultRepository.findByRaceId).not.toHaveBeenCalled();
  });

  it('should calculate SOF for completed race using results', async () => {
    const race = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      scheduledAt: new Date(),
      track: 'Track 1',
      car: 'Car 1',
      sessionType: SessionType.main(),
      status: 'completed',
    });

    raceRepository.findById.mockResolvedValue(race);
    resultRepository.findByRaceId.mockResolvedValue([
      { driverId: 'driver-1' },
      { driverId: 'driver-2' },
    ]);
    driverRatingProvider.getRatings.mockReturnValue(new Map([
      ['driver-1', 1400],
      ['driver-2', 1600],
    ]));

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.strengthOfField).toBe(1500);
    expect(dto.participantCount).toBe(2);
    expect(resultRepository.findByRaceId).toHaveBeenCalledWith('race-1');
    expect(registrationRepository.getRegisteredDrivers).not.toHaveBeenCalled();
  });

  it('should handle missing ratings gracefully', async () => {
    const race = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      scheduledAt: new Date(),
      track: 'Track 1',
      car: 'Car 1',
      sessionType: SessionType.main(),
      status: 'scheduled',
    });

    raceRepository.findById.mockResolvedValue(race);
    registrationRepository.getRegisteredDrivers.mockResolvedValue(['driver-1', 'driver-2']);
    driverRatingProvider.getRatings.mockReturnValue(new Map([
      ['driver-1', 1400],
      // driver-2 missing
    ]));

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.strengthOfField).toBe(1400); // only one rating
    expect(dto.participantCount).toBe(2);
  });

  it('should return null SOF when no participants', async () => {
    const race = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      scheduledAt: new Date(),
      track: 'Track 1',
      car: 'Car 1',
      sessionType: SessionType.main(),
      status: 'scheduled',
    });

    raceRepository.findById.mockResolvedValue(race);
    registrationRepository.getRegisteredDrivers.mockResolvedValue([]);

    const result = await useCase.execute({ raceId: 'race-1' });

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.strengthOfField).toBe(null);
    expect(dto.participantCount).toBe(0);
  });
});