import { vi, describe, it, expect, beforeEach } from 'vitest';
import { InMemorySessionRepository } from './InMemorySessionRepository';
import { Session, SessionStatus } from '@core/racing/domain/entities/Session';
import { SessionType } from '@core/racing/domain/value-objects/SessionType';
import type { Logger } from '@core/shared/application';

describe('InMemorySessionRepository', () => {
  let repository: InMemorySessionRepository;
  let mockLogger: Logger;

  beforeEach(() => {
    mockLogger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    };
    repository = new InMemorySessionRepository(mockLogger);
  });

  const createTestSession = (id: string, raceEventId: string, scheduledAt: Date, track: string, car: string, sessionType: SessionType, status?: SessionStatus) => {
    return Session.create({
      id,
      raceEventId,
      scheduledAt,
      track,
      car,
      sessionType,
      status: status || 'scheduled',
    });
  };

  describe('constructor', () => {
    it('should initialize with a logger', () => {
      expect(repository).toBeDefined();
      expect(mockLogger.info).toHaveBeenCalledWith('InMemorySessionRepository initialized.');
    });
  });

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

    it('should return the session if found', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await repository.create(session);

      const result = await repository.findById('1');
      expect(result).toEqual(session);
      expect(mockLogger.info).toHaveBeenCalledWith('Found session: 1.');
    });
  });

  describe('findAll', () => {
    it('should return all sessions', async () => {
      const session1 = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      const session2 = createTestSession('2', 'race2', new Date(), 'track2', 'car2', SessionType.qualifying());
      await repository.create(session1);
      await repository.create(session2);

      const result = await repository.findAll();
      expect(result).toHaveLength(2);
      expect(result).toContain(session1);
      expect(result).toContain(session2);
    });
  });

  describe('findByRaceEventId', () => {
    it('should return sessions for the given race event id', async () => {
      const session1 = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      const session2 = createTestSession('2', 'race1', new Date(), 'track2', 'car2', SessionType.qualifying());
      const session3 = createTestSession('3', 'race2', new Date(), 'track3', 'car3', SessionType.main());
      await repository.create(session1);
      await repository.create(session2);
      await repository.create(session3);

      const result = await repository.findByRaceEventId('race1');
      expect(result).toHaveLength(2);
      expect(result).toContain(session1);
      expect(result).toContain(session2);
    });

    it('should return empty array if no sessions for race event id', async () => {
      const result = await repository.findByRaceEventId('nonexistent');
      expect(result).toEqual([]);
    });
  });

  describe('findByLeagueId', () => {
    it('should return empty array as leagueId is not directly supported', async () => {
      const result = await repository.findByLeagueId('league1');
      expect(result).toEqual([]);
    });
  });

  describe('findByStatus', () => {
    it('should return sessions with the given status', async () => {
      const session1 = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice(), 'scheduled');
      const session2 = createTestSession('2', 'race2', new Date(), 'track2', 'car2', SessionType.qualifying(), 'running');
      await repository.create(session1);
      await repository.create(session2);

      const result = await repository.findByStatus('scheduled');
      expect(result).toHaveLength(1);
      expect(result).toContain(session1);
    });

    it('should return empty array if no sessions with status', async () => {
      const result = await repository.findByStatus('completed');
      expect(result).toEqual([]);
    });
  });

  describe('create', () => {
    it('should create a new session', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      const result = await repository.create(session);
      expect(result).toEqual(session);
      expect(mockLogger.info).toHaveBeenCalledWith('Session 1 created successfully.');
    });

    it('should throw error if session already exists', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await repository.create(session);
      await expect(repository.create(session)).rejects.toThrow('Session with ID 1 already exists');
    });
  });

  describe('update', () => {
    it('should update an existing session', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await repository.create(session);

      const updatedSession = session.start(); // Assuming start changes status
      const result = await repository.update(updatedSession);
      expect(result).toEqual(updatedSession);
      expect(mockLogger.info).toHaveBeenCalledWith('Session 1 updated successfully.');
    });

    it('should throw error if session does not exist', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await expect(repository.update(session)).rejects.toThrow('Session with ID 1 not found');
    });
  });

  describe('delete', () => {
    it('should delete an existing session', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await repository.create(session);

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

    it('should not throw error if session does not exist', async () => {
      await repository.delete('nonexistent');
      expect(mockLogger.warn).toHaveBeenCalledWith('Session with id nonexistent not found for deletion.');
    });
  });

  describe('exists', () => {
    it('should return true if session exists', async () => {
      const session = createTestSession('1', 'race1', new Date(), 'track1', 'car1', SessionType.practice());
      await repository.create(session);

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

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