import { Weight, WeightUnit } from '../../types';

const CONVERSIONS = {
  lb_to_oz: 16,
  lb_to_kg: 0.453592,
  oz_to_lb: 1 / 16,
  oz_to_kg: 0.0283495,
  kg_to_lb: 2.20462,
  kg_to_g: 1000,
  g_to_kg: 1 / 1000,
};

export function convertWeight(weight: Weight, toUnit: WeightUnit): Weight {
  if (weight.unit === toUnit) return weight;

  // Convert to kg as intermediate
  let kg: number;
  switch (weight.unit) {
    case 'lb':
      kg = weight.value * CONVERSIONS.lb_to_kg;
      break;
    case 'oz':
      kg = weight.value * CONVERSIONS.oz_to_kg;
      break;
    case 'kg':
      kg = weight.value;
      break;
    case 'g':
      kg = weight.value * CONVERSIONS.g_to_kg;
      break;
  }

  // Convert from kg to target
  let targetValue: number;
  switch (toUnit) {
    case 'lb':
      targetValue = kg * CONVERSIONS.kg_to_lb;
      break;
    case 'oz':
      targetValue = kg * CONVERSIONS.kg_to_lb * CONVERSIONS.lb_to_oz;
      break;
    case 'kg':
      targetValue = kg;
      break;
    case 'g':
      targetValue = kg * CONVERSIONS.kg_to_g;
      break;
  }

  return { value: Math.round(targetValue * 100) / 100, unit: toUnit };
}

export function formatWeight(weight: Weight): string {
  return `${weight.value} ${weight.unit}`;
}
