import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Logger } from 'vite';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import {
    GetTotalRacesUseCase,
    type GetTotalRacesErrorCode,
    type GetTotalRacesInput,
} from './GetTotalRacesUseCase';

describe('GetTotalRacesUseCase', () => {
  let useCase: GetTotalRacesUseCase;
  let raceRepository: {
    findAll: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };
  beforeEach(() => {
    raceRepository = {
      findAll: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    useCase = new GetTotalRacesUseCase(raceRepository as unknown as RaceRepository,
      logger as unknown as Logger);
  });

  it('should return total number of races', async () => {
    const races = [
      { id: 'race-1', name: 'Race 1' },
      { id: 'race-2', name: 'Race 2' },
    ];

    raceRepository.findAll.mockResolvedValue(races);

    const input: GetTotalRacesInput = {};

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const payload = result.unwrap();
    expect(payload.totalRaces).toBe(2);
  });

  it('should return error on repository failure', async () => {
    const repositoryError = new Error('Repository error');

    raceRepository.findAll.mockRejectedValue(repositoryError);

    const input: GetTotalRacesInput = {};

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);

    const errorResult = result.unwrapErr() as ApplicationErrorCode<
      GetTotalRacesErrorCode,
      { message: string }
    >;

    expect(errorResult.code).toBe('REPOSITORY_ERROR');
    expect(errorResult.details.message).toBe('Repository error');

    });
})
