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

describe('ApproveLeagueJoinRequestUseCase', () => {
  let mockLeagueMembershipRepo: {
    getJoinRequests: Mock;
    removeJoinRequest: Mock;
    saveMembership: Mock;
  };

  beforeEach(() => {
    mockLeagueMembershipRepo = {
      getJoinRequests: vi.fn(),
      removeJoinRequest: vi.fn(),
      saveMembership: vi.fn(),
    };
  });

  it('should approve join request and save membership', async () => {
    const useCase = new ApproveLeagueJoinRequestUseCase(mockLeagueMembershipRepo as unknown as ILeagueMembershipRepository);

    const leagueId = 'league-1';
    const requestId = 'req-1';
    const joinRequests = [{ id: requestId, leagueId, driverId: 'driver-1', requestedAt: new Date(), message: 'msg' }];

    mockLeagueMembershipRepo.getJoinRequests.mockResolvedValue(joinRequests);

    const result = await useCase.execute({ leagueId, requestId });

    expect(result.isOk()).toBe(true);
    expect(result.value).toEqual({ success: true, message: 'Join request approved.' });
    expect(mockLeagueMembershipRepo.removeJoinRequest).toHaveBeenCalledWith(requestId);
    expect(mockLeagueMembershipRepo.saveMembership).toHaveBeenCalledWith({
      id: expect.any(String),
      leagueId,
      driverId: 'driver-1',
      role: 'member',
      status: 'active',
      joinedAt: expect.any(Date),
    });
  });

  it('should return error if request not found', async () => {
    const useCase = new ApproveLeagueJoinRequestUseCase(mockLeagueMembershipRepo as unknown as ILeagueMembershipRepository);

    mockLeagueMembershipRepo.getJoinRequests.mockResolvedValue([]);

    const result = await useCase.execute({ leagueId: 'league-1', requestId: 'req-1' });

    expect(result.isOk()).toBe(false);
    expect(result.error!.code).toBe('JOIN_REQUEST_NOT_FOUND');
  });
});