import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetLeagueSeasonsUseCase,
  type GetLeagueSeasonsInput,
  type GetLeagueSeasonsResult,
  type GetLeagueSeasonsErrorCode,
} from './GetLeagueSeasonsUseCase';
import type { UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Season } from '../../domain/entities/season';
import { League } from '../../domain/entities/League';

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

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

    leagueRepository = {
      findById: vi.fn(),
    };

    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetLeagueSeasonsResult> & {
      present: Mock;
    };

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

  it('should present seasons with correct isParallelActive flags on success', async () => {
    const leagueId = 'league-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'A test league',
      ownerId: 'owner-1',
    });

    const seasons = [
      Season.create({
        id: 'season-1',
        leagueId,
        gameId: 'game-1',
        name: 'Season 1',
        status: 'active',
        startDate: new Date('2023-01-01'),
        endDate: new Date('2023-12-31'),
      }),
      Season.create({
        id: 'season-2',
        leagueId,
        gameId: 'game-1',
        name: 'Season 2',
        status: 'planned',
      }),
    ];

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue(seasons);

    const result = await useCase.execute({ leagueId } satisfies GetLeagueSeasonsInput);

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

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

    expect(presented?.league).toBe(league);
    expect(presented?.seasons).toHaveLength(2);

    expect(presented?.seasons[0]?.season).toBe(seasons[0]);
    expect(presented?.seasons[0]?.isPrimary).toBe(false);
    expect(presented?.seasons[0]?.isParallelActive).toBe(false);

    expect(presented?.seasons[1]?.season).toBe(seasons[1]);
    expect(presented?.seasons[1]?.isPrimary).toBe(false);
    expect(presented?.seasons[1]?.isParallelActive).toBe(false);
  });

  it('should set isParallelActive true for active seasons when multiple active', async () => {
    const leagueId = 'league-1';
    const league = League.create({
      id: leagueId,
      name: 'Test League',
      description: 'A test league',
      ownerId: 'owner-1',
    });

    const seasons = [
      Season.create({
        id: 'season-1',
        leagueId,
        gameId: 'game-1',
        name: 'Season 1',
        status: 'active',
      }),
      Season.create({
        id: 'season-2',
        leagueId,
        gameId: 'game-1',
        name: 'Season 2',
        status: 'active',
      }),
    ];

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue(seasons);

    const result = await useCase.execute({ leagueId } satisfies GetLeagueSeasonsInput);

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

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

    expect(presented?.seasons).toHaveLength(2);
    expect(presented?.seasons[0]?.isParallelActive).toBe(true);
    expect(presented?.seasons[1]?.isParallelActive).toBe(true);
  });

  it('should return LEAGUE_NOT_FOUND error when league does not exist', async () => {
    const leagueId = 'missing-league';

    leagueRepository.findById.mockResolvedValue(null);

    const result = await useCase.execute({ leagueId } satisfies GetLeagueSeasonsInput);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueSeasonsErrorCode,
      { 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 REPOSITORY_ERROR when repository throws', async () => {
    const leagueId = 'league-1';
    const errorMessage = 'DB error';

    leagueRepository.findById.mockRejectedValue(new Error(errorMessage));

    const result = await useCase.execute({ leagueId } satisfies GetLeagueSeasonsInput);

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

    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe(errorMessage);
    expect(output.present).not.toHaveBeenCalled();
  });
});