import type { Logger } from '@core/shared/domain/Logger';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import type { League } from '../../domain/entities/League';
import { Race } from '../../domain/entities/Race';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import type { SeasonRepository } from '../../domain/repositories/SeasonRepository';
import {
    GetLeagueScheduleUseCase,
    type GetLeagueScheduleErrorCode,
    type GetLeagueScheduleInput,
} from './GetLeagueScheduleUseCase';

describe('GetLeagueScheduleUseCase', () => {
  let useCase: GetLeagueScheduleUseCase;
  let leagueRepository: {
    findById: Mock;
  };
  let seasonRepository: {
    findById: Mock;
    findByLeagueId: Mock;
  };
  let raceRepository: {
    findByLeagueId: Mock;
  };
  let logger: Logger;
  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;
    useCase = new GetLeagueScheduleUseCase(leagueRepository as unknown as LeagueRepository,
      seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);
  });

  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);
    const resultValue = result.unwrap();
    expect(resultValue.league).toBe(league);
    expect(resultValue.seasonId).toBe('season-1');
    expect(resultValue.published).toBe(false);
    expect(resultValue.races).toHaveLength(1);
    expect(resultValue.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' });
    expect(resultSeason1.isOk()).toBe(true);
    const resultValue1 = resultSeason1.unwrap();
    expect(resultValue1.seasonId).toBe('season-jan');
    expect(resultValue1.published).toBe(false);
    expect(resultValue1.races.map(r => r.race.id)).toEqual(['race-jan']);

    // Season 2 covers February
    const resultSeason2 = await useCase.execute({ leagueId, seasonId: 'season-feb' });
    expect(resultSeason2.isOk()).toBe(true);
    const resultValue2 = resultSeason2.unwrap();
    expect(resultValue2.seasonId).toBe('season-feb');
    expect(resultValue2.published).toBe(false);
    expect(resultValue2.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);
    const resultValue = result.unwrap();
    expect(resultValue.league).toBe(league);
    expect(resultValue.published).toBe(false);
    expect(resultValue.races).toHaveLength(0);
  });

  it('should present all races when no seasons exist for league', async () => {
    const leagueId = 'league-1';
    const league = { id: leagueId } as unknown as League;
    const race1 = Race.create({
      id: 'race-1',
      leagueId,
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
      track: 'Track 1',
      car: 'Car 1',
    });
    const race2 = Race.create({
      id: 'race-2',
      leagueId,
      scheduledAt: new Date('2025-01-15T20:00:00Z'),
      track: 'Track 2',
      car: 'Car 2',
    });

    leagueRepository.findById.mockResolvedValue(league);
    seasonRepository.findByLeagueId.mockResolvedValue([]);
    raceRepository.findByLeagueId.mockResolvedValue([race1, race2]);

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

    expect(result.isOk()).toBe(true);
    const resultValue = result.unwrap();
    expect(resultValue.league).toBe(league);
    expect(resultValue.seasonId).toBe('no-season');
    expect(resultValue.published).toBe(false);
    expect(resultValue.races).toHaveLength(2);
    expect(resultValue.races[0]?.race).toBe(race1);
    expect(resultValue.races[1]?.race).toBe(race2);
  });

  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');
    });

  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');
    });
});