import type { Logger } from '@core/shared/domain/Logger';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { RaceRegistrationRepository } from '../../domain/repositories/RaceRegistrationRepository';
import {
    IsDriverRegisteredForRaceUseCase,
    type IsDriverRegisteredForRaceErrorCode,
    type IsDriverRegisteredForRaceInput
} from './IsDriverRegisteredForRaceUseCase';

describe('IsDriverRegisteredForRaceUseCase', () => {
  let useCase: IsDriverRegisteredForRaceUseCase;
  let registrationRepository: {
    isRegistered: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };
  beforeEach(() => {
    registrationRepository = {
      isRegistered: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    useCase = new IsDriverRegisteredForRaceUseCase(registrationRepository as unknown as RaceRegistrationRepository,
      logger as unknown as Logger);
  });

  it('should return true when driver is registered', async () => {
    const params: IsDriverRegisteredForRaceInput = { raceId: 'race-1', driverId: 'driver-1' };

    registrationRepository.isRegistered.mockResolvedValue(true);

    const result = await useCase.execute(params);

    expect(result.isOk()).toBe(true);
    });

  it('should return false when driver is not registered', async () => {
    const params: IsDriverRegisteredForRaceInput = { raceId: 'race-1', driverId: 'driver-1' };

    registrationRepository.isRegistered.mockResolvedValue(false);

    const result = await useCase.execute(params);

    expect(result.isOk()).toBe(true);
    });

  it('should return error on repository failure', async () => {
    const params: IsDriverRegisteredForRaceInput = { raceId: 'race-1', driverId: 'driver-1' };
    const error = new Error('Repository error');

    registrationRepository.isRegistered.mockRejectedValue(error);

    const result = await useCase.execute(params);

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