import type { TripEstimate } from '../types';

// Constants for carbon calculations (MGO/MDO - Marine Gas Oil / Marine Diesel Oil)
const EMISSION_FACTOR = 3.206; // tons of CO₂ per ton of fuel (MGO/MDO standard)
const FUEL_DENSITY = 0.84; // kg per liter (typical MGO density, range 0.82-0.86 kg/L)
const GALLONS_TO_LITERS = 3.78541; // 1 US gallon = 3.78541 liters
const LITERS_TO_CUBIC_METERS = 0.001; // 1 liter = 0.001 m³

export function calculateTripCarbon(
  distance: number, // nautical miles
  speed: number, // knots
  fuelRateLitersPerHour: number // liters per hour
): TripEstimate {
  const tripHours = distance / speed;

  // Calculate total fuel consumption in liters
  const fuelConsumptionLiters = fuelRateLitersPerHour * tripHours;

  // Calculate CO₂ emissions using per-nautical-mile formula
  // Guideline formula: tCO₂ per nm ≈ (LPH × 0.002693) / V
  // Implementation: tCO₂ per nm = (LPH × density × EF / 1000) / speed
  const fuelRateTonsPerHour = (fuelRateLitersPerHour * LITERS_TO_CUBIC_METERS) * FUEL_DENSITY;
  const emissionsPerNM = (fuelRateTonsPerHour * EMISSION_FACTOR) / speed;
  const totalEmissions = emissionsPerNM * distance;

  return {
    distance,
    duration: tripHours,
    fuelConsumption: Math.round(fuelConsumptionLiters),
    co2Emissions: Number(totalEmissions.toFixed(2))
  };
}

export function calculateCarbonFromFuel(fuelAmount: number, isGallons: boolean = false): number {
  // Convert to liters if input is in gallons
  const liters = isGallons ? fuelAmount * GALLONS_TO_LITERS : fuelAmount;

  // Convert liters to cubic meters (m³)
  const cubicMeters = liters * LITERS_TO_CUBIC_METERS;

  // Convert volume to mass (tons)
  const fuelTons = cubicMeters * FUEL_DENSITY;

  // Calculate CO₂ emissions: tCO₂ = t_fuel × EF
  // This implements the guideline formula: tCO₂ ≈ liters × 0.002693
  const co2Emissions = fuelTons * EMISSION_FACTOR;

  return Number(co2Emissions.toFixed(2));
}