import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { PenaltyRepository } from '../../domain/repositories/PenaltyRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import type { ResultRepository } from '../../domain/repositories/ResultRepository';
import {
    GetRaceResultsDetailUseCase,
    type GetRaceResultsDetailErrorCode,
    type GetRaceResultsDetailInput,
} from './GetRaceResultsDetailUseCase';

describe('GetRaceResultsDetailUseCase', () => {
  let useCase: GetRaceResultsDetailUseCase;
  let raceRepository: { findById: Mock };
  let leagueRepository: { findById: Mock };
  let resultRepository: { findByRaceId: Mock };
  let driverRepository: { findAll: Mock };
  let penaltyRepository: { findByRaceId: Mock };

  beforeEach(() => {
    raceRepository = { findById: vi.fn() };
    leagueRepository = { findById: vi.fn() };
    resultRepository = { findByRaceId: vi.fn() };
    driverRepository = { findAll: vi.fn() };
    penaltyRepository = { findByRaceId: vi.fn() };

    useCase = new GetRaceResultsDetailUseCase(
      raceRepository as unknown as RaceRepository,
      leagueRepository as unknown as LeagueRepository,
      resultRepository as unknown as ResultRepository,
      driverRepository as unknown as DriverRepository,
      penaltyRepository as unknown as PenaltyRepository
    );
  });

  it('presents race results detail when race exists', async () => {
    const input: GetRaceResultsDetailInput = { raceId: 'race-1' };

    const race = {
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Track 1',
      scheduledAt: new Date('2023-01-01T10:00:00Z'),
      status: 'completed' as const,
    };

    const league = {
      id: 'league-1',
      name: 'League 1',
      settings: { pointsSystem: 'f1-2024' },
    };

    const results = [
      {
        id: 'res-1',
        raceId: 'race-1',
        driverId: 'driver-1',
        position: { toNumber: () => 1 },
        fastestLap: { toNumber: () => 120 },
        incidents: { toNumber: () => 0 },
        startPosition: { toNumber: () => 1 },
      },
      {
        id: 'res-2',
        raceId: 'race-1',
        driverId: 'driver-2',
        position: { toNumber: () => 2 },
        fastestLap: { toNumber: () => 125 },
        incidents: { toNumber: () => 1 },
        startPosition: { toNumber: () => 2 },
      },
    ];

    const drivers = [
      { id: 'driver-1', name: 'Driver 1' },
      { id: 'driver-2', name: 'Driver 2' },
    ];

    const penalties = [
      {
        id: 'pen-1',
        leagueId: 'league-1',
        raceId: 'race-1',
        driverId: 'driver-1',
        type: 'time_penalty',
        value: 5,
        reason: 'cut track',
        protestId: undefined,
        issuedBy: 'steward-1',
        status: 'pending',
        issuedAt: new Date(),
        appliedAt: undefined,
        notes: undefined,
      },
    ];

    raceRepository.findById.mockResolvedValue(race);
    leagueRepository.findById.mockResolvedValue(league);
    resultRepository.findByRaceId.mockResolvedValue(results);
    driverRepository.findAll.mockResolvedValue(drivers);
    penaltyRepository.findByRaceId.mockResolvedValue(penalties);

    const result = await useCase.execute(input);

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

    expect(presented.race).toEqual(race);
    expect(presented.league).toEqual(league);
    expect(presented.results).toEqual(results);
    expect(presented.drivers).toEqual(drivers);
    expect(presented.penalties).toEqual(penalties);
    expect(presented.pointsSystem).toBeDefined();
    expect(presented.fastestLapTime).toBe(120);
  });

  it('returns error when race not found', async () => {
    const input: GetRaceResultsDetailInput = { raceId: 'race-1' };

    raceRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      GetRaceResultsDetailErrorCode,
      { message: string }
    >;

    expect(error.code).toBe('RACE_NOT_FOUND');
    expect(error.details.message).toBe('Race not found');
  });

  it('returns repository error when an unexpected error occurs', async () => {
    const input: GetRaceResultsDetailInput = { raceId: 'race-1' };

    raceRepository.findById.mockRejectedValue(new Error('Database failure'));

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      GetRaceResultsDetailErrorCode,
      { message: string }
    >;

    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details.message).toBe('Database failure');
  });
});
