import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import {
    GetTotalLeaguesUseCase,
    type GetTotalLeaguesErrorCode,
    type GetTotalLeaguesInput,
} from './GetTotalLeaguesUseCase';

describe('GetTotalLeaguesUseCase', () => {
  let useCase: GetTotalLeaguesUseCase;
  let leagueRepository: {
    findAll: Mock;
  };
  beforeEach(() => {
    leagueRepository = {
      findAll: vi.fn(),
    };

    useCase = new GetTotalLeaguesUseCase(leagueRepository as unknown as LeagueRepository);
  });

  it('should return total number of leagues', async () => {
    const leagues = [
      { id: 'league-1', name: 'League 1' },
      { id: 'league-2', name: 'League 2' },
      { id: 'league-3', name: 'League 3' },
    ];

    leagueRepository.findAll.mockResolvedValue(leagues);

    const input: GetTotalLeaguesInput = {};

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toEqual({ totalLeagues: 3 });
    });

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

    leagueRepository.findAll.mockRejectedValue(repositoryError);

    const input: GetTotalLeaguesInput = {};

    const result = await useCase.execute(input);

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

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

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