import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { Driver } from '../../domain/entities/Driver';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import {
    GetLeagueRosterJoinRequestsUseCase,
    type GetLeagueRosterJoinRequestsErrorCode,
    type GetLeagueRosterJoinRequestsInput,
} from './GetLeagueRosterJoinRequestsUseCase';

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

  let leagueMembershipRepository: {
    getJoinRequests: Mock;
  };

  let driverRepository: {
    findById: Mock;
  };

  let leagueRepository: {
    exists: Mock;
  };

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

    useCase = new GetLeagueRosterJoinRequestsUseCase(
      leagueMembershipRepository as unknown as LeagueMembershipRepository,
      driverRepository as unknown as DriverRepository,
      leagueRepository as unknown as LeagueRepository,
    );
  });

  it('returns 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);
    const successResult = result.unwrap();

    expect(successResult.joinRequests).toHaveLength(1);
    expect(successResult.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');
  });

  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');
  });
});