import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';

import { Race } from '../../domain/entities/Race';
import { Season } from '../../domain/entities/season/Season';
import type { RaceRepository } from '../../domain/repositories/RaceRepository';
import type { SeasonRepository } from '../../domain/repositories/SeasonRepository';

import { Logger } from 'vite';
import {
    CreateLeagueSeasonScheduleRaceUseCase,
    type CreateLeagueSeasonScheduleRaceErrorCode,
} from './CreateLeagueSeasonScheduleRaceUseCase';

function createLogger(): Logger {
  return {
    debug: vi.fn(),
    info: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
  } as unknown as Logger;
}

function createSeasonWithinWindow(overrides?: Partial<{ leagueId: string }>): Season {
  return Season.create({
    id: 'season-1',
    leagueId: overrides?.leagueId ?? 'league-1',
    gameId: 'iracing',
    name: 'Schedule Season',
    status: 'planned',
    startDate: new Date('2025-01-01T00:00:00Z'),
    endDate: new Date('2025-01-31T00:00:00Z'),
  });
}

describe('CreateLeagueSeasonScheduleRaceUseCase', () => {
  let seasonRepository: { findById: Mock };
  let raceRepository: { create: Mock };
  let logger: Logger;

  beforeEach(() => {
    seasonRepository = { findById: vi.fn() };
    raceRepository = { create: vi.fn() };
    logger = createLogger();
  });

  it('creates a race when season belongs to league and scheduledAt is within season window', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);
    raceRepository.create.mockImplementation(async (race: Race) => race);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    const scheduledAt = new Date('2025-01-10T20:00:00Z');
    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: 'Road Atlanta',
      car: 'MX-5',
      scheduledAt,
    });

    expect(result.isOk()).toBe(true);
    expect(raceRepository.create).toHaveBeenCalledTimes(1);
    const createdRace = raceRepository.create.mock.calls[0]?.[0] as Race;
    expect(createdRace.id).toBe('race-123');
    expect(createdRace.leagueId).toBe('league-1');
    expect(createdRace.track).toBe('Road Atlanta');
    expect(createdRace.car).toBe('MX-5');
    expect(createdRace.scheduledAt.getTime()).toBe(scheduledAt.getTime());
  });

  it('returns SEASON_NOT_FOUND when season does not belong to league and does not create', async () => {
    const season = createSeasonWithinWindow({ leagueId: 'other-league' });
    seasonRepository.findById.mockResolvedValue(season);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: 'Road Atlanta',
      car: 'MX-5',
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      CreateLeagueSeasonScheduleRaceErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('SEASON_NOT_FOUND');
    expect(raceRepository.create).not.toHaveBeenCalled();
  });


  it('returns INVALID_INPUT when Race.create throws due to invalid data', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    // Mock Race.create to throw (this would happen with invalid data)
    const originalCreate = Race.create;
    Race.create = vi.fn().mockImplementation(() => {
      throw new Error('Invalid race data');
    });

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: '', // Invalid empty track
      car: 'MX-5',
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      CreateLeagueSeasonScheduleRaceErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('INVALID_INPUT');
    expect(error.details.message).toBe('Invalid race data');
    expect(raceRepository.create).not.toHaveBeenCalled();

    // Restore original
    Race.create = originalCreate;
  });

  it('returns REPOSITORY_ERROR when repository throws during create', async () => {
    const season = createSeasonWithinWindow();
    const repositoryError = new Error('DB write failed');
    seasonRepository.findById.mockResolvedValue(season);
    raceRepository.create.mockRejectedValue(repositoryError);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: 'Road Atlanta',
      car: 'MX-5',
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      CreateLeagueSeasonScheduleRaceErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details.message).toBe('DB write failed');
  });

  it('returns SEASON_NOT_FOUND when season does not exist', async () => {
    seasonRepository.findById.mockResolvedValue(null);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: 'Road Atlanta',
      car: 'MX-5',
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      CreateLeagueSeasonScheduleRaceErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('SEASON_NOT_FOUND');
    expect(raceRepository.create).not.toHaveBeenCalled();
  });

  it('returns REPOSITORY_ERROR when repository throws during find', async () => {
    const repositoryError = new Error('DB connection failed');
    seasonRepository.findById.mockRejectedValue(repositoryError);

    const useCase = new CreateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger,
      { generateRaceId: () => 'race-123' },
    );

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      track: 'Road Atlanta',
      car: 'MX-5',
      scheduledAt: new Date('2025-01-10T20:00:00Z'),
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      CreateLeagueSeasonScheduleRaceErrorCode,
      { message: string }
    >;
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details.message).toBe('DB connection failed');
  });
});