import type { DomainCalculationService } from '@core/shared/domain/Service';

/**
 * Domain Service: StrengthOfFieldCalculator
 *
 * Calculates the Strength of Field (SOF) for a race based on participant ratings.
 * SOF is the average rating of all participants in a race.
 */

export interface DriverRating {
  driverId: string;
  rating: number;
}

export interface StrengthOfFieldCalculator {
  /**
   * Calculate SOF from a list of driver ratings
   * Returns null if no valid ratings are provided
   */
  calculate(driverRatings: DriverRating[]): number | null;
}

/**
 * Default implementation using simple average
 */
export class AverageStrengthOfFieldCalculator
  implements StrengthOfFieldCalculator, DomainCalculationService<DriverRating[], number | null>
{
  calculate(driverRatings: DriverRating[]): number | null {
    if (driverRatings.length === 0) {
      return null;
    }

    const validRatings = driverRatings.filter(dr => dr.rating > 0);
    
    if (validRatings.length === 0) {
      return null;
    }

    const sum = validRatings.reduce((acc, dr) => acc + dr.rating, 0);
    return Math.round(sum / validRatings.length);
  }
}