import { beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import {
    GetAllLeaguesWithCapacityUseCase,
    type GetAllLeaguesWithCapacityInput,
} from './GetAllLeaguesWithCapacityUseCase';

describe('GetAllLeaguesWithCapacityUseCase', () => {
  let mockLeagueRepo: { findAll: Mock };
  let mockMembershipRepo: { getLeagueMembers: Mock };

  beforeEach(() => {
    mockLeagueRepo = { findAll: vi.fn() };
    mockMembershipRepo = { getLeagueMembers: vi.fn() };
  });

  it('should return leagues with capacity information', async () => {
    const useCase = new GetAllLeaguesWithCapacityUseCase(
      mockLeagueRepo as unknown as LeagueRepository,
      mockMembershipRepo as unknown as LeagueMembershipRepository,
    );

    const league1 = { id: 'league1', name: 'Test League 1', settings: { maxDrivers: 10 } };
    const league2 = { id: 'league2', name: 'Test League 2', settings: { maxDrivers: 20 } };
    const members1 = [
      { status: 'active', role: 'member' },
      { status: 'active', role: 'owner' },
      { status: 'inactive', role: 'member' },
    ];
    const members2 = [{ status: 'active', role: 'admin' }];

    mockLeagueRepo.findAll.mockResolvedValue([league1, league2]);
    mockMembershipRepo.getLeagueMembers.mockResolvedValueOnce(members1).mockResolvedValueOnce(members2);

    const result = await useCase.execute({} as GetAllLeaguesWithCapacityInput);

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

    const resultValue = result.unwrap();
    expect(resultValue).toBeDefined();

    expect(resultValue.leagues).toHaveLength(2);

    const first = resultValue.leagues[0]!;
    const second = resultValue.leagues[1]!;

    expect(first.league).toEqual(league1);
    expect(first.currentDrivers).toBe(2);
    expect(first.maxDrivers).toBe(10);

    expect(second.league).toEqual(league2);
    expect(second.currentDrivers).toBe(1);
    expect(second.maxDrivers).toBe(20);
  });

  it('should return empty result when no leagues', async () => {
    const useCase = new GetAllLeaguesWithCapacityUseCase(
      mockLeagueRepo as unknown as LeagueRepository,
      mockMembershipRepo as unknown as LeagueMembershipRepository,
    );

    mockLeagueRepo.findAll.mockResolvedValue([]);

    const result = await useCase.execute({} as GetAllLeaguesWithCapacityInput);

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

    const resultValue = result.unwrap();
    expect(resultValue).toBeDefined();
    expect(resultValue.leagues).toEqual([]);
  });
});