import Big from 'big.js';

export type DecimalInput = string | Big;

const DEFAULT_DIVISION_DP = 20;

Big.DP = DEFAULT_DIVISION_DP;
Big.RM = Big.roundHalfEven;

function isValidDecimalString(value: string): boolean {
  return /^[-+]?((\d+\.?\d*)|(\.\d+))$/.test(value.trim());
}

export function safeBig(input: DecimalInput): Big {
  if (input instanceof Big) {
    return input;
  }

  const normalized = input.trim();
  if (!isValidDecimalString(normalized)) {
    throw new Error(`Invalid decimal input: ${input}`);
  }

  return new Big(normalized);
}
