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

describe('GetSeasonDetailsUseCase', () => {
  let useCase: GetSeasonDetailsUseCase;
  let leagueRepository: {
    findById: Mock;
  };
  let seasonRepository: {
    findById: Mock;
  };
  let output: UseCaseOutputPort<GetSeasonDetailsResult> & {
    present: Mock;
  };

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

    useCase = new GetSeasonDetailsUseCase(
      leagueRepository as unknown as ILeagueRepository,
      seasonRepository as unknown as ISeasonRepository,
      output,
    );
  });

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

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findById.mockResolvedValue(season);

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

    const result = await useCase.execute(input);

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

    expect(output.present).toHaveBeenCalledTimes(1);
    const presented =
      (output.present.mock.calls[0]?.[0] as GetSeasonDetailsResult | undefined) ??
      undefined;

    expect(presented).toBeDefined();
    expect(presented?.leagueId).toBe('league-1');
    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 league not found', async () => {
    leagueRepository.findById.mockResolvedValue(null);

    const input: GetSeasonDetailsInput = {
      leagueId: 'league-1',
      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('LEAGUE_NOT_FOUND');
    expect(error.details.message).toBe('League not found: league-1');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns error when season not found', async () => {
    const league = { id: 'league-1' };
    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findById.mockResolvedValue(null);

    const input: GetSeasonDetailsInput = {
      leagueId: 'league-1',
      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 season-1 does not belong to league league-1',
    );
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns error when season belongs to different league', async () => {
    const league = { id: 'league-1' };
    const season = Season.create({
      id: 'season-1',
      leagueId: 'league-2',
      gameId: 'iracing',
      name: 'Season',
      status: 'active',
    });

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findById.mockResolvedValue(season);

    const input: GetSeasonDetailsInput = {
      leagueId: 'league-1',
      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 season-1 does not belong to league league-1',
    );
    expect(output.present).not.toHaveBeenCalled();
  });

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

    const input: GetSeasonDetailsInput = {
      leagueId: 'league-1',
      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');
    expect(output.present).not.toHaveBeenCalled();
  });
});