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

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

  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);
    expect(output.present).toHaveBeenCalledWith({
      raceId: params.raceId,
      driverId: params.driverId,
      isRegistered: 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);
    expect(output.present).toHaveBeenCalledWith({
      raceId: params.raceId,
      driverId: params.driverId,
      isRegistered: false,
    });
  });

  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');
  });
});