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

describe('GetRacesPageDataUseCase', () => {
  let useCase: GetRacesPageDataUseCase;
  let raceRepository: RaceRepository;
  let leagueRepository: LeagueRepository;
  let logger: Logger;
  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 RaceRepository;

    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 LeagueRepository;

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

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

  it('should return 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<GetRacesPageDataResult, ApplicationErrorCode<GetRacesPageDataErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const value = result.unwrap();

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

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

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

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

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

    const result: Result<GetRacesPageDataResult, 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');
  });
});