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 {
    UpdateLeagueSeasonScheduleRaceUseCase,
    type UpdateLeagueSeasonScheduleRaceErrorCode,
} from './UpdateLeagueSeasonScheduleRaceUseCase';

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('UpdateLeagueSeasonScheduleRaceUseCase', () => {
  let seasonRepository: { findById: Mock };
  let raceRepository: { findById: Mock; update: Mock };
  let logger: Logger;

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

  it('updates race when season belongs to league and updated scheduledAt stays within window', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);
    raceRepository.update.mockImplementation(async (race: Race) => race);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const newScheduledAt = new Date('2025-01-20T20:00:00Z');
    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
      car: 'New Car',
      scheduledAt: newScheduledAt,
    });

    expect(result.isOk()).toBe(true);
    expect(raceRepository.update).toHaveBeenCalledTimes(1);
    const updated = raceRepository.update.mock.calls[0]?.[0] as Race;
    expect(updated.id).toBe('race-1');
    expect(updated.leagueId).toBe('league-1');
    expect(updated.track).toBe('New Track');
    expect(updated.car).toBe('New Car');
    expect(updated.scheduledAt.getTime()).toBe(newScheduledAt.getTime());
  });

  it('updates race with partial fields (only track)', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);
    raceRepository.update.mockImplementation(async (race: Race) => race);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

    expect(result.isOk()).toBe(true);
    expect(raceRepository.update).toHaveBeenCalledTimes(1);
    const updated = raceRepository.update.mock.calls[0]?.[0] as Race;
    expect(updated.track).toBe('New Track');
    expect(updated.car).toBe('Old Car'); // Unchanged
    expect(updated.scheduledAt.getTime()).toBe(existing.scheduledAt.getTime()); // Unchanged
  });

  it('updates race with partial fields (only car)', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);
    raceRepository.update.mockImplementation(async (race: Race) => race);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      car: 'New Car',
    });

    expect(result.isOk()).toBe(true);
    expect(raceRepository.update).toHaveBeenCalledTimes(1);
    const updated = raceRepository.update.mock.calls[0]?.[0] as Race;
    expect(updated.track).toBe('Old Track'); // Unchanged
    expect(updated.car).toBe('New Car');
    expect(updated.scheduledAt.getTime()).toBe(existing.scheduledAt.getTime()); // Unchanged
  });

  it('updates race with partial fields (only scheduledAt)', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);
    raceRepository.update.mockImplementation(async (race: Race) => race);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const newScheduledAt = new Date('2025-01-15T20:00:00Z');
    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      scheduledAt: newScheduledAt,
    });

    expect(result.isOk()).toBe(true);
    expect(raceRepository.update).toHaveBeenCalledTimes(1);
    const updated = raceRepository.update.mock.calls[0]?.[0] as Race;
    expect(updated.track).toBe('Old Track'); // Unchanged
    expect(updated.car).toBe('Old Car'); // Unchanged
    expect(updated.scheduledAt.getTime()).toBe(newScheduledAt.getTime());
  });

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

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

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

  it('returns RACE_OUTSIDE_SEASON_WINDOW when updated scheduledAt is outside window and does not update', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      scheduledAt: new Date('2025-02-01T00:00:01Z'),
    });

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

  it('returns RACE_NOT_FOUND when race does not exist for league and does not update', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);
    raceRepository.findById.mockResolvedValue(null);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-404',
      track: 'New Track',
    });

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

  it('returns RACE_NOT_FOUND when race belongs to different league', async () => {
    const season = createSeasonWithinWindow();
    seasonRepository.findById.mockResolvedValue(season);

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'other-league',
      track: 'Track',
      car: 'Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

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

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

    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    raceRepository.findById.mockResolvedValue(existing);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    // Mock Race.create to throw
    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',
      raceId: 'race-1',
      track: '', // Invalid
    });

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

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

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

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

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

  it('returns REPOSITORY_ERROR when repository throws during update', async () => {
    const season = createSeasonWithinWindow();
    const existing = Race.create({
      id: 'race-1',
      leagueId: 'league-1',
      track: 'Old Track',
      car: 'Old Car',
      scheduledAt: new Date('2025-01-05T20:00:00Z'),
    });
    const repositoryError = new Error('DB write failed');
    seasonRepository.findById.mockResolvedValue(season);
    raceRepository.findById.mockResolvedValue(existing);
    raceRepository.update.mockRejectedValue(repositoryError);

    const useCase = new UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as ApplicationErrorCode<
      UpdateLeagueSeasonScheduleRaceErrorCode,
      { 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 UpdateLeagueSeasonScheduleRaceUseCase(seasonRepository as unknown as SeasonRepository,
      raceRepository as unknown as RaceRepository,
      logger);

    const result = await useCase.execute({
      leagueId: 'league-1',
      seasonId: 'season-1',
      raceId: 'race-1',
      track: 'New Track',
    });

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