import { describe, it, expect, vi } from 'vitest';
import { UpdateLeagueMemberRoleUseCase } from './UpdateLeagueMemberRoleUseCase';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';

describe('UpdateLeagueMemberRoleUseCase', () => {
  it('updates league member role successfully', async () => {
    const mockMembership = {
      leagueId: 'league-1',
      driverId: 'driver-1',
      role: 'member',
      status: 'active',
      joinedAt: new Date(),
    };

    const mockLeagueMembershipRepository = {
      getLeagueMembers: vi.fn().mockResolvedValue([mockMembership]),
      saveMembership: vi.fn().mockResolvedValue(undefined),
    } as unknown as ILeagueMembershipRepository;

    const useCase = new UpdateLeagueMemberRoleUseCase(mockLeagueMembershipRepository);

    const params = {
      leagueId: 'league-1',
      targetDriverId: 'driver-1',
      newRole: 'admin',
    };

    const result = await useCase.execute(params);

    expect(result.isOk()).toBe(true);
    expect(mockLeagueMembershipRepository.getLeagueMembers).toHaveBeenCalledWith('league-1');
    expect(mockLeagueMembershipRepository.saveMembership).toHaveBeenCalledWith({
      ...mockMembership,
      role: 'admin',
    });
  });

  it('returns error if membership not found', async () => {
    const mockLeagueMembershipRepository = {
      getLeagueMembers: vi.fn().mockResolvedValue([]),
    } as unknown as ILeagueMembershipRepository;

    const useCase = new UpdateLeagueMemberRoleUseCase(mockLeagueMembershipRepository);

    const params = {
      leagueId: 'league-1',
      targetDriverId: 'driver-1',
      newRole: 'admin',
    };

    const result = await useCase.execute(params);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({ code: 'MEMBERSHIP_NOT_FOUND' });
  });
});