/**
 * Integration Test: Race Results Use Case Orchestration
 * 
 * Tests the orchestration logic of race results page-related Use Cases:
 * - GetRaceResultsDetailUseCase: Retrieves complete race results (all finishers)
 * - GetRacePenaltiesUseCase: Retrieves race penalties and incidents
 * 
 * Adheres to Clean Architecture:
 * - Tests Core Use Cases directly
 * - Uses In-Memory adapters for repositories
 * - Follows Given/When/Then pattern
 * 
 * Focus: Business logic orchestration, NOT UI rendering
 */

import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
import { InMemoryRaceRepository } from '../../../adapters/racing/persistence/inmemory/InMemoryRaceRepository';
import { InMemoryLeagueRepository } from '../../../adapters/racing/persistence/inmemory/InMemoryLeagueRepository';
import { InMemoryDriverRepository } from '../../../adapters/racing/persistence/inmemory/InMemoryDriverRepository';
import { InMemoryResultRepository } from '../../../adapters/racing/persistence/inmemory/InMemoryResultRepository';
import { InMemoryPenaltyRepository } from '../../../adapters/racing/persistence/inmemory/InMemoryPenaltyRepository';
import { GetRaceResultsDetailUseCase } from '../../../core/racing/application/use-cases/GetRaceResultsDetailUseCase';
import { GetRacePenaltiesUseCase } from '../../../core/racing/application/use-cases/GetRacePenaltiesUseCase';
import { Race } from '../../../core/racing/domain/entities/Race';
import { League } from '../../../core/racing/domain/entities/League';
import { Driver } from '../../../core/racing/domain/entities/Driver';
import { Result as RaceResult } from '../../../core/racing/domain/entities/result/Result';
import { Penalty } from '../../../core/racing/domain/entities/penalty/Penalty';
import { Logger } from '../../../core/shared/domain/Logger';

describe('Race Results Use Case Orchestration', () => {
  let raceRepository: InMemoryRaceRepository;
  let leagueRepository: InMemoryLeagueRepository;
  let driverRepository: InMemoryDriverRepository;
  let resultRepository: InMemoryResultRepository;
  let penaltyRepository: InMemoryPenaltyRepository;
  let getRaceResultsDetailUseCase: GetRaceResultsDetailUseCase;
  let getRacePenaltiesUseCase: GetRacePenaltiesUseCase;
  let mockLogger: Logger;

  beforeAll(() => {
    mockLogger = {
      info: () => {},
      debug: () => {},
      warn: () => {},
      error: () => {},
    } as unknown as Logger;

    raceRepository = new InMemoryRaceRepository(mockLogger);
    leagueRepository = new InMemoryLeagueRepository(mockLogger);
    driverRepository = new InMemoryDriverRepository(mockLogger);
    resultRepository = new InMemoryResultRepository(mockLogger, raceRepository);
    penaltyRepository = new InMemoryPenaltyRepository(mockLogger);

    getRaceResultsDetailUseCase = new GetRaceResultsDetailUseCase(
      raceRepository,
      leagueRepository,
      resultRepository,
      driverRepository,
      penaltyRepository
    );

    getRacePenaltiesUseCase = new GetRacePenaltiesUseCase(
      penaltyRepository,
      driverRepository
    );
  });

  beforeEach(async () => {
    (raceRepository as any).races.clear();
    leagueRepository.clear();
    await driverRepository.clear();
    (resultRepository as any).results.clear();
    (penaltyRepository as any).penalties.clear();
  });

  describe('GetRaceResultsDetailUseCase', () => {
    it('should retrieve complete race results with all finishers', async () => {
      // Given: A completed race with results
      const leagueId = 'l1';
      const league = League.create({ id: leagueId, name: 'Pro League', description: 'Desc', ownerId: 'o1' });
      await leagueRepository.create(league);

      const raceId = 'r1';
      const race = Race.create({
        id: raceId,
        leagueId,
        scheduledAt: new Date(Date.now() - 86400000),
        track: 'Spa',
        car: 'GT3',
        status: 'completed'
      });
      await raceRepository.create(race);

      const driverId = 'd1';
      const driver = Driver.create({ id: driverId, iracingId: '100', name: 'John Doe', country: 'US' });
      await driverRepository.create(driver);

      const raceResult = RaceResult.create({
        id: 'res1',
        raceId,
        driverId,
        position: 1,
        lapsCompleted: 20,
        totalTime: 3600,
        fastestLap: 105,
        points: 25
      });
      await resultRepository.create(raceResult);

      // When: GetRaceResultsDetailUseCase.execute() is called
      const result = await getRaceResultsDetailUseCase.execute({ raceId });

      // Then: The result should contain race and results
      expect(result.isOk()).toBe(true);
      const data = result.unwrap();
      expect(data.race.id).toBe(raceId);
      expect(data.results).toHaveLength(1);
      expect(data.results[0].driverId.toString()).toBe(driverId);
    });
  });

  describe('GetRacePenaltiesUseCase', () => {
    it('should retrieve race penalties with driver information', async () => {
      // Given: A race with penalties
      const raceId = 'r1';
      const driverId = 'd1';
      const stewardId = 's1';

      const driver = Driver.create({ id: driverId, iracingId: '100', name: 'John Doe', country: 'US' });
      await driverRepository.create(driver);
      
      const steward = Driver.create({ id: stewardId, iracingId: '200', name: 'Steward', country: 'UK' });
      await driverRepository.create(steward);

      const penalty = Penalty.create({
        id: 'p1',
        raceId,
        driverId,
        type: 'time',
        value: 5,
        reason: 'Track limits',
        issuedBy: stewardId,
        status: 'applied'
      });
      await penaltyRepository.create(penalty);

      // When: GetRacePenaltiesUseCase.execute() is called
      const result = await getRacePenaltiesUseCase.execute({ raceId });

      // Then: It should return penalties and drivers
      expect(result.isOk()).toBe(true);
      const data = result.unwrap();
      expect(data.penalties).toHaveLength(1);
      expect(data.drivers.some(d => d.id === driverId)).toBe(true);
      expect(data.drivers.some(d => d.id === stewardId)).toBe(true);
    });
  });
});
