import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import {
  GetLeagueScoringConfigUseCase,
  type GetLeagueScoringConfigResult,
  type GetLeagueScoringConfigInput,
  type GetLeagueScoringConfigErrorCode,
} from './GetLeagueScoringConfigUseCase';
import { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';
import { ILeagueScoringConfigRepository } from '../../domain/repositories/ILeagueScoringConfigRepository';
import { IGameRepository } from '../../domain/repositories/IGameRepository';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

describe('GetLeagueScoringConfigUseCase', () => {
  let useCase: GetLeagueScoringConfigUseCase;
  let leagueRepository: { findById: Mock };
  let seasonRepository: { findByLeagueId: Mock };
  let leagueScoringConfigRepository: { findBySeasonId: Mock };
  let gameRepository: { findById: Mock };
  let presetProvider: { getPresetById: Mock };
  let output: UseCaseOutputPort<GetLeagueScoringConfigResult> & { present: Mock };

  beforeEach(() => {
    leagueRepository = { findById: vi.fn() };
    seasonRepository = { findByLeagueId: vi.fn() };
    leagueScoringConfigRepository = { findBySeasonId: vi.fn() };
    gameRepository = { findById: vi.fn() };
    presetProvider = { getPresetById: vi.fn() };
    output = { present: vi.fn() } as unknown as UseCaseOutputPort<GetLeagueScoringConfigResult> & {
      present: Mock;
    };
    useCase = new GetLeagueScoringConfigUseCase(
      leagueRepository as unknown as ILeagueRepository,
      seasonRepository as unknown as ISeasonRepository,
      leagueScoringConfigRepository as unknown as ILeagueScoringConfigRepository,
      gameRepository as unknown as IGameRepository,
      presetProvider,
      output,
    );
  });

  it('should return scoring config for active season', async () => {
    const input: GetLeagueScoringConfigInput = { leagueId: 'league-1' };
    const league = { id: input.leagueId };
    const season = { id: 'season-1', status: 'active', gameId: 'game-1' };
    const scoringConfig = { scoringPresetId: 'preset-1', championships: [] };
    const game = { id: 'game-1', name: 'Game 1' };
    const preset = { id: 'preset-1', name: 'Preset 1' };

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([season]);
    leagueScoringConfigRepository.findBySeasonId.mockResolvedValue(scoringConfig);
    gameRepository.findById.mockResolvedValue(game);
    presetProvider.getPresetById.mockReturnValue(preset);

    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 GetLeagueScoringConfigResult;
    expect(presented?.league).toEqual(league);
    expect(presented?.season).toEqual(season);
    expect(presented?.scoringConfig).toEqual(scoringConfig);
    expect(presented?.game).toEqual(game);
    expect(presented?.preset).toEqual(preset);
  });

  it('should return scoring config for first season if no active', async () => {
    const input: GetLeagueScoringConfigInput = { leagueId: 'league-1' };
    const league = { id: input.leagueId };
    const season = { id: 'season-1', status: 'inactive', gameId: 'game-1' };
    const scoringConfig = { scoringPresetId: undefined, championships: [] };
    const game = { id: 'game-1', name: 'Game 1' };

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([season]);
    leagueScoringConfigRepository.findBySeasonId.mockResolvedValue(scoringConfig);
    gameRepository.findById.mockResolvedValue(game);

    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 GetLeagueScoringConfigResult;
    expect(presented?.league).toEqual(league);
    expect(presented?.season).toEqual(season);
    expect(presented?.scoringConfig).toEqual(scoringConfig);
    expect(presented?.game).toEqual(game);
    expect(presented?.preset).toBeUndefined();
  });

  it('should return error if league not found', async () => {
    leagueRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('LEAGUE_NOT_FOUND');
    expect(err.details.message).toBe('League not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error if no seasons', async () => {
    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    seasonRepository.findByLeagueId.mockResolvedValue([]);

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('NO_SEASONS');
    expect(err.details.message).toBe('No seasons found for league');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error if no seasons (null)', async () => {
    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    seasonRepository.findByLeagueId.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('NO_SEASONS');
    expect(err.details.message).toBe('No seasons found for league');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error if no scoring config', async () => {
    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    seasonRepository.findByLeagueId.mockResolvedValue([
      { id: 'season-1', status: 'active', gameId: 'game-1' },
    ]);
    leagueScoringConfigRepository.findBySeasonId.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('NO_SCORING_CONFIG');
    expect(err.details.message).toBe('Scoring configuration not found');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should return error if game not found', async () => {
    leagueRepository.findById.mockResolvedValue({ id: 'league-1' });
    seasonRepository.findByLeagueId.mockResolvedValue([
      { id: 'season-1', status: 'active', gameId: 'game-1' },
    ]);
    leagueScoringConfigRepository.findBySeasonId.mockResolvedValue({
      scoringPresetId: undefined,
      championships: [],
    });
    gameRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('GAME_NOT_FOUND');
    expect(err.details.message).toBe('Game not found for season');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('should wrap repository errors', async () => {
    leagueRepository.findById.mockRejectedValue(new Error('db down'));

    const result = await useCase.execute({ leagueId: 'league-1' });

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScoringConfigErrorCode,
      { message: string }
    >;
    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('db down');
    expect(output.present).not.toHaveBeenCalled();
  });
});