import Decimal from 'decimal.js';
import { array as A, ord as Ord } from 'fp-ts';

/**
 * Plutus division behaves differently when working with negative numbers vs positive ones.
 */
export function divideOnChainCompatible(a: bigint, b: bigint): bigint {
  const res = a / b;
  return res + (res < 0n ? -1n : 0n);
}

export function bigintMax(a: bigint, b: bigint): bigint {
  return a > b ? a : b;
}

export function bigintMin(a: bigint, b: bigint): bigint {
  return a < b ? a : b;
}

export function sum(arr: bigint[]): bigint {
  return A.reduce<bigint, bigint>(0n, (acc, val) => acc + val)(arr);
}

export function fromDecimal(val: Decimal): bigint {
  return BigInt(val.toString());
}

export function zeroNegatives(a: bigint): bigint {
  return bigintMax(0n, a);
}

export const BigIntOrd: Ord.Ord<bigint> = {
  equals: (x, y) => x === y,
  compare: (first, second) => (first < second ? -1 : first > second ? 1 : 0),
};
