import { Result } from '@core/racing/domain/entities/result/Result';
import type { Logger } from '@core/shared/domain/Logger';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { InMemoryResultRepository } from './InMemoryResultRepository';

describe('InMemoryResultRepository', () => {
  let repository: InMemoryResultRepository;
  let mockLogger: Logger;
  let mockRaceRepository: IRaceRepository;

  beforeEach(() => {
    mockLogger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    mockRaceRepository = {
      findById: vi.fn(),
      findAll: vi.fn(),
      findByLeagueId: vi.fn(),
      findUpcomingByLeagueId: vi.fn(),
      findCompletedByLeagueId: vi.fn(),
      findByStatus: vi.fn(),
      findByDateRange: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      exists: vi.fn(),
    } as any; // eslint-disable-line @typescript-eslint/no-explicit-any
    repository = new InMemoryResultRepository(mockLogger, mockRaceRepository);
  });

  const createTestResult = (
    id: string,
    raceId: string,
    driverId: string,
    position: number,
    fastestLap: number = 120.5,
    incidents: number = 0,
    startPosition: number = position
  ) => {
    return Result.create({
      id,
      raceId,
      driverId,
      position,
      fastestLap,
      incidents,
      startPosition,
    });
  };

  describe('constructor', () => {
    it('should initialize with a logger and race repository', () => {
      expect(repository).toBeDefined();
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Initialized.');
    });
  });

  describe('findById', () => {
    it('should return null if result not found', async () => {
      const result = await repository.findById('nonexistent');
      expect(result).toBeNull();
      expect(mockLogger.debug).toHaveBeenCalledWith('[InMemoryResultRepository] Finding result by id: nonexistent');
      expect(mockLogger.warn).toHaveBeenCalledWith('[InMemoryResultRepository] Result with id nonexistent not found.');
    });

    it('should return the result if found', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);

      const found = await repository.findById('1');
      expect(found).toEqual(result);
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Found result with id: 1.');
    });
  });

  describe('findAll', () => {
    it('should return all results', async () => {
      const result1 = createTestResult('1', 'race1', 'driver1', 1);
      const result2 = createTestResult('2', 'race1', 'driver2', 2);
      await repository.create(result1);
      await repository.create(result2);

      const results = await repository.findAll();
      expect(results).toHaveLength(2);
      expect(results).toContain(result1);
      expect(results).toContain(result2);
    });
  });

  describe('findByRaceId', () => {
    it('should return results filtered by race ID', async () => {
      const result1 = createTestResult('1', 'race1', 'driver1', 1);
      const result2 = createTestResult('2', 'race2', 'driver2', 1);
      const result3 = createTestResult('3', 'race1', 'driver3', 2);
      await repository.create(result1);
      await repository.create(result2);
      await repository.create(result3);

      const results = await repository.findByRaceId('race1');
      expect(results).toHaveLength(2);
      expect(results).toContain(result1);
      expect(results).toContain(result3);
      expect(results[0]?.id).toBe('1'); // sorted by position
      expect(results[1]?.id).toBe('3');
    });
  });

  describe('findByDriverId', () => {
    it('should return results filtered by driver ID', async () => {
      const result1 = createTestResult('1', 'race1', 'driver1', 1);
      const result2 = createTestResult('2', 'race2', 'driver1', 2);
      const result3 = createTestResult('3', 'race1', 'driver2', 1);
      await repository.create(result1);
      await repository.create(result2);
      await repository.create(result3);

      const results = await repository.findByDriverId('driver1');
      expect(results).toHaveLength(2);
      expect(results).toContain(result1);
      expect(results).toContain(result2);
    });
  });

  describe('findByDriverIdAndLeagueId', () => {
    it('should return results for driver in league', async () => {
      const result1 = createTestResult('1', 'race1', 'driver1', 1);
      const result2 = createTestResult('2', 'race2', 'driver1', 2);
      await repository.create(result1);
      await repository.create(result2);

      (mockRaceRepository.findByLeagueId as any).mockResolvedValue([ // eslint-disable-line @typescript-eslint/no-explicit-any
        { id: 'race1' } as { id: string },
      ]);

      const results = await repository.findByDriverIdAndLeagueId('driver1', 'league1');
      expect(results).toHaveLength(1);
      expect(results).toContain(result1);
    });

    it('should return empty if no race repository', async () => {
      repository = new InMemoryResultRepository(mockLogger); // no race repo
      const results = await repository.findByDriverIdAndLeagueId('driver1', 'league1');
      expect(results).toHaveLength(0);
    });
  });

  describe('create', () => {
    it('should create a new result', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      const created = await repository.create(result);
      expect(created).toEqual(result);
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Result 1 created successfully.');
    });

    it('should throw error if result already exists', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);
      await expect(repository.create(result)).rejects.toThrow('Result with ID 1 already exists');
    });
  });

  describe('createMany', () => {
    it('should create multiple results', async () => {
      const results = [
        createTestResult('1', 'race1', 'driver1', 1),
        createTestResult('2', 'race1', 'driver2', 2),
      ];
      const created = await repository.createMany(results);
      expect(created).toHaveLength(2);
      expect(created).toContain(results[0]);
      expect(created).toContain(results[1]);
    });
  });

  describe('update', () => {
    it('should update an existing result', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);

      const updated = createTestResult('1', 'race1', 'driver1', 2);
      const result2 = await repository.update(updated);
      expect(result2).toEqual(updated);
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Result 1 updated successfully.');
    });

    it('should throw error if result does not exist', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await expect(repository.update(result)).rejects.toThrow('Result with ID 1 not found');
    });
  });

  describe('delete', () => {
    it('should delete an existing result', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);

      await repository.delete('1');
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Result 1 deleted successfully.');
      const found = await repository.findById('1');
      expect(found).toBeNull();
    });

    it('should throw error if result does not exist', async () => {
      await expect(repository.delete('nonexistent')).rejects.toThrow('Result with ID nonexistent not found');
    });
  });

  describe('deleteByRaceId', () => {
    it('should delete results for a race', async () => {
      const result1 = createTestResult('1', 'race1', 'driver1', 1);
      const result2 = createTestResult('2', 'race2', 'driver2', 1);
      await repository.create(result1);
      await repository.create(result2);

      await repository.deleteByRaceId('race1');
      expect(mockLogger.info).toHaveBeenCalledWith('[InMemoryResultRepository] Deleted 1 results for race id: race1.');
      const found = await repository.findById('1');
      expect(found).toBeNull();
      const found2 = await repository.findById('2');
      expect(found2).toEqual(result2);
    });
  });

  describe('exists', () => {
    it('should return true if result exists', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);

      const exists = await repository.exists('1');
      expect(exists).toBe(true);
    });

    it('should return false if result does not exist', async () => {
      const exists = await repository.exists('nonexistent');
      expect(exists).toBe(false);
    });
  });

  describe('existsByRaceId', () => {
    it('should return true if results exist for race', async () => {
      const result = createTestResult('1', 'race1', 'driver1', 1);
      await repository.create(result);

      const exists = await repository.existsByRaceId('race1');
      expect(exists).toBe(true);
    });

    it('should return false if no results for race', async () => {
      const exists = await repository.existsByRaceId('nonexistent');
      expect(exists).toBe(false);
    });
  });
});