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

describe('GetLeagueAdminUseCase', () => {
  let mockLeagueRepo: ILeagueRepository;
  let mockFindById: Mock;
  let output: UseCaseOutputPort<GetLeagueAdminResult> & { present: 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(),
    } as ILeagueRepository;

    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetLeagueAdminResult> & { present: Mock };
  });

  const createUseCase = () => new GetLeagueAdminUseCase(
    mockLeagueRepo,
    output,
  );

  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');
    expect(output.present).not.toHaveBeenCalled();
  });

  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);
    expect(result.unwrap()).toBeUndefined();
    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]?.[0] as GetLeagueAdminResult;
    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');
    expect(output.present).not.toHaveBeenCalled();
  });
});