import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
import {
  GetLeagueScheduleUseCase,
  type GetLeagueScheduleInput,
  type GetLeagueScheduleResult,
  type GetLeagueScheduleErrorCode,
} from './GetLeagueScheduleUseCase';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { League } from '../../domain/entities/League';
import { Race } from '../../domain/entities/Race';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';

describe('GetLeagueScheduleUseCase', () => {
  let useCase: GetLeagueScheduleUseCase;
  let leagueRepository: {
    findById: Mock;
  };
  let seasonRepository: {
    findById: Mock;
    findByLeagueId: Mock;
  };
  let raceRepository: {
    findByLeagueId: Mock;
  };
  let logger: Logger;
  let output: UseCaseOutputPort<GetLeagueScheduleResult> & { present: Mock };

  beforeEach(() => {
    leagueRepository = {
      findById: vi.fn(),
    };
    seasonRepository = {
      findById: vi.fn(),
      findByLeagueId: vi.fn(),
    };
    raceRepository = {
      findByLeagueId: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;
    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<GetLeagueScheduleResult> & { present: Mock };

    useCase = new GetLeagueScheduleUseCase(
      leagueRepository as unknown as ILeagueRepository,
      seasonRepository as any,
      raceRepository as unknown as IRaceRepository,
      logger,
      output,
    );
  });

  it('should present league schedule when races exist', async () => {
    const leagueId = 'league-1';
    const league = { id: leagueId } as unknown as League;
    const race = Race.create({
      id: 'race-1',
      leagueId,
      scheduledAt: new Date('2023-01-01T10:00:00Z'),
      track: 'Track 1',
      car: 'Car 1',
    });

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([
      { id: 'season-1', leagueId, status: { isActive: () => true } },
    ]);
    raceRepository.findByLeagueId.mockResolvedValue([race]);

    const input: GetLeagueScheduleInput = { leagueId };
    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 GetLeagueScheduleResult;

    expect(presented.league).toBe(league);
    expect(presented.seasonId).toBe('season-1');
    expect(presented.published).toBe(false);
    expect(presented.races).toHaveLength(1);
    expect(presented.races[0]?.race).toBe(race);
  });

  it('should scope schedule by seasonId (no season bleed)', async () => {
    const leagueId = 'league-1';
    const league = { id: leagueId } as unknown as League;

    const janRace = Race.create({
      id: 'race-jan',
      leagueId,
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
      track: 'Track Jan',
      car: 'Car Jan',
    });

    const febRace = Race.create({
      id: 'race-feb',
      leagueId,
      scheduledAt: new Date('2025-02-10T20:00:00Z'),
      track: 'Track Feb',
      car: 'Car Feb',
    });

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findById.mockImplementation(async (id: string) => {
      if (id === 'season-jan') {
        return { id, leagueId, startDate: new Date('2025-01-01T00:00:00Z'), endDate: new Date('2025-01-31T23:59:59Z') };
      }
      if (id === 'season-feb') {
        return { id, leagueId, startDate: new Date('2025-02-01T00:00:00Z'), endDate: new Date('2025-02-28T23:59:59Z') };
      }
      return null;
    });
    raceRepository.findByLeagueId.mockResolvedValue([janRace, febRace]);

    // Season 1 covers January
    const resultSeason1 = await useCase.execute({ leagueId, seasonId: 'season-jan' } as any);
    expect(resultSeason1.isOk()).toBe(true);

    const presented1 = output.present.mock.calls.at(-1)?.[0] as any;
    expect(presented1.seasonId).toBe('season-jan');
    expect(presented1.published).toBe(false);
    expect((presented1.races as GetLeagueScheduleResult['races']).map(r => r.race.id)).toEqual(['race-jan']);

    // Season 2 covers February
    const resultSeason2 = await useCase.execute({ leagueId, seasonId: 'season-feb' } as any);
    expect(resultSeason2.isOk()).toBe(true);

    const presented2 = output.present.mock.calls.at(-1)?.[0] as any;
    expect(presented2.seasonId).toBe('season-feb');
    expect(presented2.published).toBe(false);
    expect((presented2.races as GetLeagueScheduleResult['races']).map(r => r.race.id)).toEqual(['race-feb']);
  });

  it('should present empty schedule when no races exist', async () => {
    const leagueId = 'league-1';
    const league = { id: leagueId } as unknown as League;

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([
      { id: 'season-1', leagueId, status: { isActive: () => true } },
    ]);
    raceRepository.findByLeagueId.mockResolvedValue([]);

    const input: GetLeagueScheduleInput = { leagueId };
    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 GetLeagueScheduleResult;

    expect(presented.league).toBe(league);
    expect(presented.published).toBe(false);
    expect(presented.races).toHaveLength(0);
  });

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

    leagueRepository.findById.mockResolvedValue(null);

    const input: GetLeagueScheduleInput = { leagueId };
    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<
      GetLeagueScheduleErrorCode,
      { 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 league = { id: leagueId } as unknown as League;
    const repositoryError = new Error('DB down');

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([
      { id: 'season-1', leagueId, status: { isActive: () => true } },
    ]);
    raceRepository.findByLeagueId.mockRejectedValue(repositoryError);

    const input: GetLeagueScheduleInput = { leagueId };
    const result = await useCase.execute(input);

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

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