import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { Season } from '../../domain/entities/season/Season';
import type { SeasonRepository } from '../../domain/repositories/SeasonRepository';
import {
    GetSeasonDetailsUseCase,
    type GetSeasonDetailsErrorCode,
    type GetSeasonDetailsInput,
} from './GetSeasonDetailsUseCase';

describe('GetSeasonDetailsUseCase', () => {
  let useCase: GetSeasonDetailsUseCase;
  let seasonRepository: {
    findById: Mock;
  };

  beforeEach(() => {
    seasonRepository = {
      findById: vi.fn(),
    };

    useCase = new GetSeasonDetailsUseCase(seasonRepository as unknown as SeasonRepository);
  });

  it('returns full details for a season', async () => {
    const season = Season.create({
      id: 'season-1',
      leagueId: 'league-1',
      gameId: 'iracing',
      name: 'Detailed Season',
      status: 'planned',
    }).withMaxDrivers(24);

    seasonRepository.findById.mockResolvedValue(season);

    const input: GetSeasonDetailsInput = {
      seasonId: 'season-1',
    };

    const result = await useCase.execute(input);

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

    expect(presented).toBeDefined();
    expect(presented.season.id).toBe('season-1');
    expect(presented.season.leagueId).toBe('league-1');
    expect(presented.season.gameId).toBe('iracing');
    expect(presented.season.name).toBe('Detailed Season');
    expect(presented.season.status.toString()).toBe('planned');
    expect(presented.season.maxDrivers).toBe(24);
  });

  it('returns error when season not found', async () => {
    seasonRepository.findById.mockResolvedValue(null);

    const input: GetSeasonDetailsInput = {
      seasonId: 'season-1',
    };

    const result = await useCase.execute(input);

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

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

    expect(error.code).toBe('SEASON_NOT_FOUND');
    expect(error.details.message).toBe('Season not found');
  });

  it('returns repository error when an unexpected exception occurs', async () => {
    seasonRepository.findById.mockRejectedValue(
      new Error('Unexpected repository failure'),
    );

    const input: GetSeasonDetailsInput = {
      seasonId: 'season-1',
    };

    const result = await useCase.execute(input);

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

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

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