import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetLeagueRosterJoinRequestsUseCase,
  type GetLeagueRosterJoinRequestsInput,
  type GetLeagueRosterJoinRequestsResult,
  type GetLeagueRosterJoinRequestsErrorCode,
} from './GetLeagueRosterJoinRequestsUseCase';
import type { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Driver } from '../../domain/entities/Driver';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';

describe('GetLeagueRosterJoinRequestsUseCase', () => {
  let useCase: GetLeagueRosterJoinRequestsUseCase;

  let leagueMembershipRepository: {
    getJoinRequests: Mock;
  };

  let driverRepository: {
    findById: Mock;
  };

  let leagueRepository: {
    exists: Mock;
  };

  let output: UseCaseOutputPort<GetLeagueRosterJoinRequestsResult> & { present: Mock };

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

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

  it('presents only join requests with resolvable drivers', async () => {
    const leagueId = 'league-1';
    const requestedAt = new Date('2025-01-02T03:04:05.000Z');

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

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

    leagueRepository.exists.mockResolvedValue(true);
    leagueMembershipRepository.getJoinRequests.mockResolvedValue(joinRequests);
    driverRepository.findById.mockImplementation((id: string) => {
      if (id === 'driver-1') return Promise.resolve(driver1);
      return Promise.resolve(null);
    });

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

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

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

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

  it('returns LEAGUE_NOT_FOUND when league does not exist', async () => {
    leagueRepository.exists.mockResolvedValue(false);

    const result = await useCase.execute({ leagueId: 'missing' } as GetLeagueRosterJoinRequestsInput);

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

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

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

  it('returns REPOSITORY_ERROR when repository throws', async () => {
    leagueRepository.exists.mockRejectedValue(new Error('Repository failure'));

    const result = await useCase.execute({ leagueId: 'league-1' } as GetLeagueRosterJoinRequestsInput);

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

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

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