/**
 * Persisted line weight (kg) for PR / PO / inward / GRN lines.
 * Uses explicit client value when valid; else net_weight (or gross_weight) × quantity on material master.
 */

function parsePositiveDecimal(v) {
  const n = parseFloat(v);
  return Number.isFinite(n) && n > 0 ? n : null;
}

/**
 * @param {object} opts
 * @param {number|string} opts.quantity - line qty (PR/PO/GRN qty or inward received qty)
 * @param {number|string|null} [opts.line_weight_kg] - optional explicit weight from client
 * @param {object|null} [opts.material] - Sequelize Material or plain row with net_weight / gross_weight
 * @returns {number|null}
 */
function computeLineWeightKg({ quantity, line_weight_kg: clientWeight, material }) {
  const explicit = parsePositiveDecimal(clientWeight);
  if (explicit != null) return round3(explicit);

  const q = parsePositiveDecimal(quantity);
  if (q == null || !material) return null;

  const raw =
    material.net_weight != null && material.net_weight !== ''
      ? parseFloat(material.net_weight)
      : parseFloat(material.gross_weight);
  if (!Number.isFinite(raw) || raw <= 0) return null;

  return round3(raw * q);
}

function round3(n) {
  return Math.round(n * 1000) / 1000;
}

module.exports = {
  computeLineWeightKg,
};
