import { Decimal } from '@rms/domain';

const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));

/**
 * One unit's part of a meter, as a debit note shows it: "1/3" for an even
 * split, "1/6" or "1/18" reduced from whole-number shares (6 of 36, 2 of 36), a
 * percentage when a share has decimals — and nothing for a meter that covers a
 * single unit.
 */
export function sharePart(shares: readonly Decimal[], index: number): string {
  if (shares.length <= 1) return '';
  const total = shares.reduce((a, s) => a.plus(s), new Decimal(0));
  const mine = shares[index];
  if (mine.isInteger() && total.isInteger()) {
    const g = gcd(mine.toNumber(), total.toNumber());
    return `${mine.toNumber() / g}/${total.toNumber() / g}`;
  }
  return `${mine.dividedBy(total).times(100).toDecimalPlaces(2).toString()}%`;
}
