import { REFERENCE_UNIT_CODES } from "@open-mercato/shared/lib/units/unitCodes";
import { canonicalizeUnitCode } from "../../lib/unitCodes.js";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
const UNIT_PRICE_REFERENCE_UNITS = new Set(REFERENCE_UNIT_CODES);
function toTrimmedOrNull(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length ? trimmed : null;
}
function parseNumericInput(value) {
  if (typeof value === "number") return value;
  if (typeof value === "string") {
    const normalized = value.trim().replace(/\s+/g, "").replace(/,/g, ".");
    if (!normalized.length) return Number.NaN;
    return Number(normalized);
  }
  return Number(value);
}
function toPositiveNumberOrNull(value) {
  const numeric = parseNumericInput(value);
  if (!Number.isFinite(numeric) || numeric <= 0) return null;
  return numeric;
}
function toIntegerInRangeOrDefault(value, min, max, fallback) {
  const numeric = parseNumericInput(value);
  if (!Number.isInteger(numeric) || numeric < min || numeric > max)
    return fallback;
  return numeric;
}
function normalizeProductConversionInputs(rows, duplicateMessage) {
  const list = Array.isArray(rows) ? rows : [];
  const normalized = [];
  const seen = /* @__PURE__ */ new Set();
  for (const row of list) {
    const unitCode = canonicalizeUnitCode(row?.unitCode);
    const toBaseFactor = toPositiveNumberOrNull(row?.toBaseFactor);
    if (!unitCode || toBaseFactor === null) continue;
    const unitKey = unitCode.toLowerCase();
    if (seen.has(unitKey)) {
      throw createCrudFormError(duplicateMessage, {
        unitConversions: duplicateMessage
      });
    }
    seen.add(unitKey);
    normalized.push({
      id: toTrimmedOrNull(row?.id),
      unitCode,
      toBaseFactor,
      sortOrder: toIntegerInRangeOrDefault(
        row?.sortOrder,
        0,
        1e5,
        normalized.length * 10
      ),
      isActive: row?.isActive !== false
    });
  }
  return normalized;
}
export {
  UNIT_PRICE_REFERENCE_UNITS,
  normalizeProductConversionInputs,
  parseNumericInput,
  toIntegerInRangeOrDefault,
  toPositiveNumberOrNull,
  toTrimmedOrNull
};
//# sourceMappingURL=productFormUtils.js.map
