import { describe, it, expect, beforeEach, vi, Mock } from 'vitest';
import { ListSeasonsForLeagueUseCase } from './ListSeasonsForLeagueUseCase';
import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Season } from '../../domain/entities/Season';

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

  beforeEach(() => {
    leagueRepository = {
      findById: vi.fn(),
    };
    seasonRepository = {
      listByLeague: vi.fn(),
    };
    useCase = new ListSeasonsForLeagueUseCase(
      leagueRepository as unknown as ILeagueRepository,
      seasonRepository as unknown as ISeasonRepository,
    );
  });

  it('lists seasons for a league with summaries', async () => {
    const league = { id: 'league-1' };
    const seasons = [
      Season.create({
        id: 'season-1',
        leagueId: 'league-1',
        gameId: 'iracing',
        name: 'Season One',
        status: 'planned',
      }),
      Season.create({
        id: 'season-2',
        leagueId: 'league-1',
        gameId: 'iracing',
        name: 'Season Two',
        status: 'active',
      }),
    ];

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

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

    expect(result.isOk()).toBe(true);
    const dto = result.unwrap();
    expect(dto.items.map((i) => i.seasonId).sort()).toEqual([
      'season-1',
      'season-2',
    ]);
    expect(dto.items.every((i) => i.leagueId === 'league-1')).toBe(true);
  });

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

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

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'LEAGUE_NOT_FOUND',
      details: { message: 'League not found: league-1' },
    });
  });

});