import { UnitConversionService, UnitSystem } from './unit-conversion.service';

export interface EfficiencyResult {
  value: number;
  unitSystem: UnitSystem;
  label: string;
  calculationMethod: 'odometer' | 'trip_distance';
}

export interface PartialEnhancedLog {
  odometerReading?: number;
  tripDistance?: number;
  fuelUnits?: number;
}

export class EfficiencyCalculationService {
  static calculateEfficiency(
    currentLog: PartialEnhancedLog,
    previousOdometerReading: number | null,
    unitSystem: UnitSystem
  ): EfficiencyResult | null {
    let distance: number | undefined;
    let method: 'odometer' | 'trip_distance' | undefined;

    if (currentLog.tripDistance && currentLog.tripDistance > 0) {
      distance = currentLog.tripDistance;
      method = 'trip_distance';
    } else if (currentLog.odometerReading && previousOdometerReading !== null) {
      const d = currentLog.odometerReading - previousOdometerReading;
      if (d > 0) {
        distance = d;
        method = 'odometer';
      }
    }

    if (!distance || !currentLog.fuelUnits || currentLog.fuelUnits <= 0 || !method) {
      return null;
    }

    const value = UnitConversionService.calculateEfficiency(distance, currentLog.fuelUnits);
    const labels = UnitConversionService.getUnitLabels(unitSystem);
    return { value, unitSystem, label: labels.efficiencyUnits, calculationMethod: method };
  }
}

