import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Logger } from 'vite';
import { beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import { LeagueMembership } from '../../domain/entities/LeagueMembership';
import { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import { JoinLeagueUseCase, type JoinLeagueErrorCode, type JoinLeagueInput } from './JoinLeagueUseCase';

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 LeagueMembershipRepository,
      logger as unknown as Logger);
  });

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

    membershipRepository.getMembership.mockResolvedValue(null);
    membershipRepository.saveMembership.mockResolvedValue(
      LeagueMembership.create({
        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);
    const presented = result.unwrap();

    expect(presented.membership.id).toBe('membership-1');
    expect(presented.membership.leagueId.toString()).toBe('league-1');
    expect(presented.membership.driverId.toString()).toBe('driver-1');
    expect(presented.membership.role.toString()).toBe('member');
    expect(presented.membership.status.toString()).toBe('active');
  });

  it('should return error when already a member', async () => {
    const command: JoinLeagueInput = { 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);
    const err = result.unwrapErr() as ApplicationErrorCode<JoinLeagueErrorCode, { message: string }>;
    expect(err.code).toBe('ALREADY_MEMBER');
    expect(err.details?.message).toBe('Driver is already a member of this league or has a pending membership.');
    });

  it('should return error on repository failure', async () => {
    const command: JoinLeagueInput = { 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);
    const err = result.unwrapErr() as ApplicationErrorCode<JoinLeagueErrorCode, { message: string }>;
    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details?.message).toBe('Repository error');
    });
});