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

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

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

  it('applies activate → complete → archive transitions and persists state', async () => {
    const league = { id: 'league-1' };
    let currentSeason = Season.create({
      id: 'season-1',
      leagueId: 'league-1',
      gameId: 'iracing',
      name: 'Lifecycle Season',
      status: 'planned',
    });

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findById.mockImplementation(() => Promise.resolve(currentSeason));
    seasonRepository.update.mockImplementation((s) => {
      currentSeason = s;
      return Promise.resolve(s);
    });

    const activateCommand: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: currentSeason.id,
      transition: 'activate',
    };

    const activated = await useCase.execute(activateCommand);
    expect(activated.isOk()).toBe(true);
    expect(activated.unwrap().status).toBe('active');

    const completeCommand: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: currentSeason.id,
      transition: 'complete',
    };

    const completed = await useCase.execute(completeCommand);
    expect(completed.isOk()).toBe(true);
    expect(completed.unwrap().status).toBe('completed');

    const archiveCommand: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: currentSeason.id,
      transition: 'archive',
    };

    const archived = await useCase.execute(archiveCommand);
    expect(archived.isOk()).toBe(true);
    expect(archived.unwrap().status).toBe('archived');
  });

  it('propagates domain invariant errors for invalid transitions', async () => {
    const league = { id: 'league-1' };
    const season = Season.create({
      id: 'season-1',
      leagueId: 'league-1',
      gameId: 'iracing',
      name: 'Lifecycle Season',
      status: 'planned',
    });

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

    const completeCommand: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: season.id,
      transition: 'complete',
    };

    const result = await useCase.execute(completeCommand);
    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toEqual('INVALID_TRANSITION');
  });

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

    const command: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: 'season-1',
      transition: 'activate',
    };

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

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

    const command: ManageSeasonLifecycleCommand = {
      leagueId: 'league-1',
      seasonId: 'season-1',
      transition: 'activate',
    };

    const result = await useCase.execute(command);
    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({
      code: 'SEASON_NOT_FOUND',
      details: { message: 'Season season-1 does not belong to league league-1' },
    });
  });
});