import { RacesApiClient } from '../../api/races/RacesApiClient';
import { ProtestsApiClient } from '../../api/protests/ProtestsApiClient';
import { PenaltiesApiClient } from '../../api/penalties/PenaltiesApiClient';
import { RaceStewardingViewModel } from '../../view-models/RaceStewardingViewModel';

/**
 * Race Stewarding Service
 *
 * Orchestrates race stewarding operations by coordinating API calls for race details,
 * protests, and penalties, and returning a unified view model.
 */
export class RaceStewardingService {
  constructor(
    private readonly racesApiClient: RacesApiClient,
    private readonly protestsApiClient: ProtestsApiClient,
    private readonly penaltiesApiClient: PenaltiesApiClient
  ) {}

  /**
   * Get race stewarding data with view model transformation
   */
  async getRaceStewardingData(raceId: string, driverId: string): Promise<RaceStewardingViewModel> {
    // Fetch all data in parallel
    const [raceDetail, protests, penalties] = await Promise.all([
      this.racesApiClient.getDetail(raceId, driverId),
      this.protestsApiClient.getRaceProtests(raceId),
      this.penaltiesApiClient.getRacePenalties(raceId),
    ]);

    // Convert API responses to match RaceStewardingViewModel expectations
    const convertedProtests = {
      protests: protests.protests.map(p => ({
        id: p.id,
        protestingDriverId: p.protestingDriverId,
        accusedDriverId: p.accusedDriverId,
        incident: {
          lap: p.lap,
          description: p.description
        },
        filedAt: p.filedAt,
        status: p.status
      })),
      driverMap: Object.entries(protests.driverMap).reduce((acc, [id, name]) => {
        acc[id] = { id, name: name as string };
        return acc;
      }, {} as Record<string, { id: string; name: string }>)
    };

    const convertedPenalties = {
      penalties: penalties.penalties.map(p => ({
        id: p.id,
        driverId: p.driverId,
        type: p.type,
        value: p.value,
        reason: p.reason,
        notes: p.notes
      })),
      driverMap: Object.entries(penalties.driverMap).reduce((acc, [id, name]) => {
        acc[id] = { id, name: name as string };
        return acc;
      }, {} as Record<string, { id: string; name: string }>)
    };

    return new RaceStewardingViewModel({
      raceDetail,
      protests: convertedProtests,
      penalties: convertedPenalties,
    });
  }
}