import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetRacesPageDataUseCase,
  type GetRacesPageDataResult,
  type GetRacesPageDataInput,
  type GetRacesPageDataErrorCode,
} from './GetRacesPageDataUseCase';
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Result } from '@core/shared/application/Result';

describe('GetRacesPageDataUseCase', () => {
  let useCase: GetRacesPageDataUseCase;
  let raceRepository: IRaceRepository;
  let leagueRepository: ILeagueRepository;
  let logger: Logger;
  let output: UseCaseOutputPort<GetRacesPageDataResult> & { present: Mock };

  beforeEach(() => {
    const raceFindAll = vi.fn();
    const leagueFindAll = vi.fn();

    raceRepository = {
      findById: vi.fn(),
      findAll: raceFindAll,
      findByLeagueId: vi.fn(),
      findUpcomingByLeagueId: vi.fn(),
      findCompletedByLeagueId: vi.fn(),
      findByStatus: vi.fn(),
      findByDateRange: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      exists: vi.fn(),
    } as unknown as IRaceRepository;

    leagueRepository = {
      findById: vi.fn(),
      findAll: leagueFindAll,
      findByOwnerId: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      exists: vi.fn(),
      searchByName: vi.fn(),
    } as unknown as ILeagueRepository;

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetRacesPageDataResult> & { present: Mock };

    useCase = new GetRacesPageDataUseCase(raceRepository, leagueRepository, logger, output);
  });

  it('should present races page data for a league', async () => {
    type RaceRow = {
      id: string;
      track: string;
      car: string;
      scheduledAt: Date;
      status: 'scheduled' | 'completed';
      leagueId: string;
      strengthOfField: number;
      isUpcoming: () => boolean;
      isLive: () => boolean;
      isPast: () => boolean;
    };

    type LeagueRow = { id: string; name: string };

    const races: RaceRow[] = [
      {
        id: 'race-1',
        track: 'Track 1',
        car: 'Car 1',
        scheduledAt: new Date('2023-01-01T10:00:00Z'),
        status: 'scheduled',
        leagueId: 'league-1',
        strengthOfField: 1500,
        isUpcoming: () => true,
        isLive: () => false,
        isPast: () => false,
      },
      {
        id: 'race-2',
        track: 'Track 2',
        car: 'Car 2',
        scheduledAt: new Date('2023-01-02T10:00:00Z'),
        status: 'completed',
        leagueId: 'league-1',
        strengthOfField: 1600,
        isUpcoming: () => false,
        isLive: () => false,
        isPast: () => true,
      },
    ];

    const leagues: LeagueRow[] = [{ id: 'league-1', name: 'League 1' }];

    (raceRepository.findAll as Mock).mockResolvedValue(races);
    (leagueRepository.findAll as Mock).mockResolvedValue(leagues);

    const input: GetRacesPageDataInput = { leagueId: 'league-1' };

    const result: Result<void, ApplicationErrorCode<GetRacesPageDataErrorCode, { message: string }>> =
      await useCase.execute(input);

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

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

    expect(presented.leagueId).toBe('league-1');
    expect(presented.races).toHaveLength(2);

    expect(presented.races[0]!.race.id).toBe('race-1');
    expect(presented.races[0]!.leagueName).toBe('League 1');
    expect(presented.races[1]!.race.id).toBe('race-2');
  });

  it('should return repository error when repositories throw and not present data', async () => {
    const error = new Error('Repository error');

    (raceRepository.findAll as Mock).mockRejectedValue(error);

    const input: GetRacesPageDataInput = { leagueId: 'league-1' };

    const result: Result<void, ApplicationErrorCode<GetRacesPageDataErrorCode, { message: string }>> =
      await useCase.execute(input);

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

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

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