export const sanitizeNumericInput = (value) => String(value || '').replace(/\D/g, '');

const getExerciseRange = (exercise, subType = null) => {
  if (subType && exercise?.subValueRanges?.[subType]) {
    return exercise.subValueRanges[subType];
  }

  return {
    minValue: exercise?.minValue,
    maxValue: exercise?.maxValue
  };
};

export const normalizeExerciseValue = (exercise, value, subType = null) => {
  const sanitizedValue = sanitizeNumericInput(value);

  if (!sanitizedValue) {
    return '';
  }

  const parsedValue = Number.parseInt(sanitizedValue, 10);
  const range = getExerciseRange(exercise, subType);
  const minValue = Number.isFinite(range?.minValue) ? range.minValue : 0;
  const maxValue = Number.isFinite(range?.maxValue) ? range.maxValue : null;

  const clampedValue = maxValue === null
    ? Math.max(parsedValue, minValue)
    : Math.min(Math.max(parsedValue, minValue), maxValue);

  return String(clampedValue);
};
