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

describe('GetLeagueAdminUseCase', () => {
  let mockLeagueRepo: {
    findById: Mock;
    findAll: Mock;
    create: Mock;
    update: Mock;
    delete: Mock;
    exists: Mock;
    findByOwnerId: Mock;
    searchByName: Mock;
  };
  let mockFindById: Mock;

  beforeEach(() => {
    mockFindById = vi.fn();
    mockLeagueRepo = {
      findById: mockFindById,
      findAll: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      exists: vi.fn(),
      findByOwnerId: vi.fn(),
      searchByName: vi.fn(),
    };
  });

  const createUseCase = () => new GetLeagueAdminUseCase(mockLeagueRepo as unknown as LeagueRepository);

  const params: GetLeagueAdminInput = {
    leagueId: 'league1',
  };

  it('should return error when league not found', async () => {
    mockFindById.mockResolvedValue(null);

    const useCase = createUseCase();
    const result = await useCase.execute(params);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<GetLeagueAdminErrorCode, { message: string }>;
    expect(error.code).toBe('LEAGUE_NOT_FOUND');
    expect(error.details.message).toBe('League not found');
  });

  it('should return league data when league found', async () => {
    const league = { id: 'league1', ownerId: 'owner1' };
    mockFindById.mockResolvedValue(league);

    const useCase = createUseCase();
    const result = await useCase.execute(params);

    expect(result.isOk()).toBe(true);
    const presented = result.unwrap();
    expect(presented.league.id).toBe('league1');
    expect(presented.league.ownerId).toBe('owner1');
  });

  it('should return repository error when repository throws', async () => {
    const repoError = new Error('Repository failure');
    mockFindById.mockRejectedValue(repoError);

    const useCase = createUseCase();
    const result = await useCase.execute(params);

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