import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { PenaltyRepository } from '../../domain/repositories/PenaltyRepository';
import {
    GetRacePenaltiesUseCase,
    type GetRacePenaltiesErrorCode,
    type GetRacePenaltiesInput,
} from './GetRacePenaltiesUseCase';

describe('GetRacePenaltiesUseCase', () => {
  let useCase: GetRacePenaltiesUseCase;
  let penaltyRepository: { findByRaceId: Mock };
  let driverRepository: { findById: Mock };
  beforeEach(() => {
    penaltyRepository = { findByRaceId: vi.fn() };
    driverRepository = { findById: vi.fn() };
    useCase = new GetRacePenaltiesUseCase(penaltyRepository as unknown as PenaltyRepository,
      driverRepository as unknown as DriverRepository);
  });

  it('should return penalties with drivers', async () => {
    const input: GetRacePenaltiesInput = { raceId: 'race-1' };
    const penalties = [
      {
        id: 'penalty-1',
        raceId: input.raceId,
        driverId: 'driver-1',
        issuedBy: 'driver-2',
        type: 'time' as const,
        value: 10,
        reason: 'Reason 1',
        status: 'applied' as const,
        issuedAt: new Date(),
      },
    ];
    const drivers = [
      { id: 'driver-1', name: 'Driver 1' },
      { id: 'driver-2', name: 'Driver 2' },
    ];

    penaltyRepository.findByRaceId.mockResolvedValue(penalties);
    driverRepository.findById.mockImplementation((id) => Promise.resolve(drivers.find((d) => d.id === id)));

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const resultValue = result.unwrap();
    expect(resultValue.penalties).toEqual(penalties);
    expect(resultValue.drivers).toEqual(drivers);
  });

  it('should return empty when no penalties', async () => {
    penaltyRepository.findByRaceId.mockResolvedValue([]);
    driverRepository.findById.mockResolvedValue(null);

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

    expect(result.isOk()).toBe(true);
    const resultValue = result.unwrap();
    expect(resultValue.penalties).toEqual([]);
    expect(resultValue.drivers).toEqual([]);
  });

  it('should return repository error when repository throws', async () => {
    const input: GetRacePenaltiesInput = { raceId: 'race-1' };
    const repositoryError = new Error('Repository failure');
    penaltyRepository.findByRaceId.mockRejectedValue(repositoryError);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetRacePenaltiesErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('Repository failure');
    });
});