// Package decimal provides money helpers on shopspring/decimal.
// Money is NUMERIC(15,2); quantities NUMERIC(12,4). Never float.
package decimal

import (
	"errors"

	"github.com/shopspring/decimal"
)

// ParseMoney parses a string into a decimal with 2 dp (NUMERIC(15,2) parity).
// "3996000" -> 3996000.00; "12.345" rounds to 12.35.
func ParseMoney(s string) (decimal.Decimal, error) {
	if s == "" {
		return decimal.Zero, nil
	}
	d, err := decimal.NewFromString(s)
	if err != nil {
		return decimal.Decimal{}, err
	}
	return d.Round(2), nil
}

// ParseQuantity parses a string into a decimal with up to 4 dp (NUMERIC(12,4)).
func ParseQuantity(s string) (decimal.Decimal, error) {
	if s == "" {
		return decimal.Zero, nil
	}
	d, err := decimal.NewFromString(s)
	if err != nil {
		return decimal.Decimal{}, err
	}
	return d.Round(4), nil
}

// Money2 forces 2dp (used before Persist).
func Money2(d decimal.Decimal) decimal.Decimal { return d.Round(2) }

// Quantity4 forces 4dp.
func Quantity4(d decimal.Decimal) decimal.Decimal { return d.Round(4) }

// NonNegative errors when d < 0. Used to guard totals (Laravel max(0, ...)).
func NonNegative(d decimal.Decimal) error {
	if d.IsNegative() {
		return errors.New("value must not be negative")
	}
	return nil
}

// ZeroFromInt is a convenience for integer literals in tests.
func ZeroFromInt(i int) decimal.Decimal {
	return decimal.NewFromInt(int64(i))
}
