import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { JoinLeagueUseCase } from './JoinLeagueUseCase';
import { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { Logger } from '@core/shared/application';

describe('JoinLeagueUseCase', () => {
  let useCase: JoinLeagueUseCase;
  let membershipRepository: {
    getMembership: Mock;
    saveMembership: Mock;
  };
  let logger: {
    debug: Mock;
    info: Mock;
    warn: Mock;
    error: Mock;
  };

  beforeEach(() => {
    membershipRepository = {
      getMembership: vi.fn(),
      saveMembership: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    useCase = new JoinLeagueUseCase(
      membershipRepository as unknown as ILeagueMembershipRepository,
      logger as unknown as Logger,
    );
  });

  it('should join league successfully', async () => {
    const command = { leagueId: 'league-1', driverId: 'driver-1' };

    membershipRepository.getMembership.mockResolvedValue(null);
    membershipRepository.saveMembership.mockResolvedValue({
      id: 'membership-1',
      leagueId: 'league-1',
      driverId: 'driver-1',
      role: 'member',
      status: 'active',
      joinedAt: new Date(),
    });

    const result = await useCase.execute(command);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toEqual({
      id: 'membership-1',
      leagueId: 'league-1',
      driverId: 'driver-1',
      role: 'member',
      status: 'active',
      joinedAt: expect.any(Date),
    });
  });

  it('should return error when already a member', async () => {
    const command = { leagueId: 'league-1', driverId: 'driver-1' };

    membershipRepository.getMembership.mockResolvedValue({
      id: 'membership-1',
      leagueId: 'league-1',
      driverId: 'driver-1',
      role: 'member',
      status: 'active',
      joinedAt: new Date(),
    });

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'ALREADY_MEMBER',
      details: { message: 'Already a member or have a pending request' },
    });
  });

  it('should return error on repository failure', async () => {
    const command = { leagueId: 'league-1', driverId: 'driver-1' };
    const error = new Error('Repository error');

    membershipRepository.getMembership.mockRejectedValue(error);

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'REPOSITORY_ERROR',
      details: { message: 'Repository error' },
    });
  });
});