export function formatRanchDate(value, options = {}) {
  if (!value) return '—';
  const raw = String(value).slice(0, 10);
  const date = new Date(`${raw}T12:00:00`);
  if (Number.isNaN(date.getTime())) return String(value);

  return new Intl.DateTimeFormat('es-MX', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    ...options,
  }).format(date);
}

export function formatMoney(value) {
  if (value === null || value === undefined || value === '') return '—';
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(Number(value));
}

export function formatQuantity(value, unit = '') {
  if (value === null || value === undefined || value === '') return '—';
  const qty = Number(value);
  const formatted = Number.isInteger(qty) ? String(qty) : qty.toFixed(2);
  return unit ? `${formatted} ${unit}` : formatted;
}

export function healthEventDose(event) {
  const unit = event?.material_type?.unit || 'ml';
  const qty = event?.material_expense?.quantity;
  if (qty !== null && qty !== undefined && qty !== '') {
    return formatQuantity(qty, unit);
  }

  const notes = String(event?.notes || '');
  const match = notes.match(/Dosis\s+([\d.]+)\s*(ml|dosis|kg|l|litro)?/i);
  if (match) {
    return formatQuantity(match[1], match[2] || unit);
  }

  return '—';
}
