import { FuelType, FuelGrade, EnhancedCreateFuelLogRequest } from './fuel-logs.types';
import { FuelGradeService } from './fuel-grade.service';

export interface ValidationResult {
  isValid: boolean;
  errors: string[];
  warnings: string[];
}

export class EnhancedValidationService {
  static validateFuelLogData(data: Partial<EnhancedCreateFuelLogRequest>): ValidationResult {
    const errors: string[] = [];
    const warnings: string[] = [];

    // Distance requirement
    const hasOdo = data.odometerReading && data.odometerReading > 0;
    const hasTrip = data.tripDistance && data.tripDistance > 0;
    if (!hasOdo && !hasTrip) errors.push('Either odometer reading or trip distance is required');
    if (hasOdo && hasTrip) errors.push('Cannot specify both odometer reading and trip distance');

    // Fuel type/grade
    if (!data.fuelType) errors.push('Fuel type is required');
    if (data.fuelType && !Object.values(FuelType).includes(data.fuelType)) {
      errors.push(`Invalid fuel type: ${data.fuelType}`);
    } else if (data.fuelType && !FuelGradeService.isValidGradeForFuelType(data.fuelType, data.fuelGrade as FuelGrade)) {
      errors.push(`Invalid fuel grade '${data.fuelGrade}' for fuel type '${data.fuelType}'`);
    }

    // Numeric
    if (data.fuelUnits !== undefined && data.fuelUnits <= 0) errors.push('Fuel units must be positive');
    if (data.costPerUnit !== undefined && data.costPerUnit <= 0) errors.push('Cost per unit must be positive');
    if (data.odometerReading !== undefined && data.odometerReading <= 0) errors.push('Odometer reading must be positive');
    if (data.tripDistance !== undefined && data.tripDistance <= 0) errors.push('Trip distance must be positive');

    // Date/time
    if (data.dateTime) {
      const dt = new Date(data.dateTime);
      const now = new Date();
      if (isNaN(dt.getTime())) errors.push('Invalid date/time format');
      if (dt > now) errors.push('Cannot create fuel logs in the future');
    }

    // Heuristics warnings
    if (data.fuelUnits && data.fuelUnits > 100) warnings.push('Fuel amount seems unusually high (>100 units)');
    if (data.costPerUnit && data.costPerUnit > 10) warnings.push('Cost per unit seems unusually high (>$10)');
    if (data.tripDistance && data.tripDistance > 1000) warnings.push('Trip distance seems unusually high (>1000 miles)');

    return { isValid: errors.length === 0, errors, warnings };
  }
}
