import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { GetLeagueMembershipsUseCase } from './GetLeagueMembershipsUseCase';
import { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { LeagueMembership } from '../../domain/entities/LeagueMembership';
import { Driver } from '../../domain/entities/Driver';

describe('GetLeagueMembershipsUseCase', () => {
  let useCase: GetLeagueMembershipsUseCase;
  let leagueMembershipRepository: {
    getLeagueMembers: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };

  beforeEach(() => {
    leagueMembershipRepository = {
      getLeagueMembers: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    useCase = new GetLeagueMembershipsUseCase(
      leagueMembershipRepository as unknown as ILeagueMembershipRepository,
      driverRepository as unknown as IDriverRepository,
    );
  });

  it('should return league memberships with drivers', async () => {
    const leagueId = 'league-1';
    const memberships = [
      LeagueMembership.create({
        id: 'membership-1',
        leagueId,
        driverId: 'driver-1',
        role: 'member',
        joinedAt: new Date(),
      }),
      LeagueMembership.create({
        id: 'membership-2',
        leagueId,
        driverId: 'driver-2',
        role: 'admin',
        joinedAt: new Date(),
      }),
    ];
    const driver1 = Driver.create({
      id: 'driver-1',
      iracingId: '123',
      name: 'Driver 1',
      country: 'US',
    });
    const driver2 = Driver.create({
      id: 'driver-2',
      iracingId: '456',
      name: 'Driver 2',
      country: 'UK',
    });

    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    driverRepository.findById.mockImplementation((id: string) => {
      if (id === 'driver-1') return Promise.resolve(driver1);
      if (id === 'driver-2') return Promise.resolve(driver2);
      return Promise.resolve(null);
    });

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

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toEqual({
      memberships,
      drivers: [
        { id: 'driver-1', name: 'Driver 1' },
        { id: 'driver-2', name: 'Driver 2' },
      ],
    });
  });

  it('should handle drivers not found', async () => {
    const leagueId = 'league-1';
    const memberships = [
      LeagueMembership.create({
        id: 'membership-1',
        leagueId,
        driverId: 'driver-1',
        role: 'member',
        joinedAt: new Date(),
      }),
    ];

    leagueMembershipRepository.getLeagueMembers.mockResolvedValue(memberships);
    driverRepository.findById.mockResolvedValue(null);

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

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toEqual({
      memberships,
      drivers: [],
    });
  });
});