import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetLeagueJoinRequestsUseCase,
  type GetLeagueJoinRequestsInput,
  type GetLeagueJoinRequestsResult,
  type GetLeagueJoinRequestsErrorCode,
} from './GetLeagueJoinRequestsUseCase';
import { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Driver } from '../../domain/entities/Driver';
import type { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetLeagueJoinRequestsUseCase', () => {
  let useCase: GetLeagueJoinRequestsUseCase;
  let leagueMembershipRepository: {
    getJoinRequests: Mock;
  };
  let driverRepository: {
    findById: Mock;
  };
  let leagueRepository: {
    exists: Mock;
  };
  let output: UseCaseOutputPort<GetLeagueJoinRequestsResult> & { present: Mock };

  beforeEach(() => {
    leagueMembershipRepository = {
      getJoinRequests: vi.fn(),
    };
    driverRepository = {
      findById: vi.fn(),
    };
    leagueRepository = {
      exists: vi.fn(),
    };
    output = {
      present: vi.fn(),
    };

    useCase = new GetLeagueJoinRequestsUseCase(
      leagueMembershipRepository as unknown as ILeagueMembershipRepository,
      driverRepository as unknown as IDriverRepository,
      leagueRepository as unknown as ILeagueRepository,
      output,
    );
  });

  it('should return join requests with drivers when league exists', async () => {
    const leagueId = 'league-1';
    const input: GetLeagueJoinRequestsInput = { leagueId };

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

    const driver = Driver.create({
      id: 'driver-1',
      iracingId: '123',
      name: 'Driver 1',
      country: 'US',
    });

    leagueRepository.exists.mockResolvedValue(true);
    leagueMembershipRepository.getJoinRequests.mockResolvedValue(joinRequests);
    driverRepository.findById.mockResolvedValue(driver);

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented = output.present.mock.calls[0]?.[0] as GetLeagueJoinRequestsResult;

    expect(presented.joinRequests).toHaveLength(1);
    expect(presented.joinRequests[0]).toMatchObject({
      id: 'req-1',
      leagueId,
      driverId: 'driver-1',
      message: 'msg',
    });
    expect(presented?.joinRequests[0]?.driver).toBe(driver);
  });

  it('should return LEAGUE_NOT_FOUND error when league does not exist', async () => {
    const leagueId = 'missing-league';
    const input: GetLeagueJoinRequestsInput = { leagueId };

    leagueRepository.exists.mockResolvedValue(false);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueJoinRequestsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('LEAGUE_NOT_FOUND');
    expect(err.details.message).toBe('League not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return REPOSITORY_ERROR when repository throws', async () => {
    const leagueId = 'league-1';
    const input: GetLeagueJoinRequestsInput = { leagueId };
    const error = new Error('Repository failure');

    leagueRepository.exists.mockRejectedValue(error);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueJoinRequestsErrorCode,
      { message: string }
    >;

    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('Repository failure');
    expect(output.present).not.toHaveBeenCalled();
  });
});
