export enum SatcommaFormat {
  BTC = 'BTC',
  SATS = 'SATS',
}

const SATS_PER_BTC = 100_000_000;

function formatSatsGroup(sats: number): string {
  return (
    sats
      .toString()
      .split('')
      .reverse()
      .join('')
      .match(/.{1,3}/g)
      ?.reverse()
      .map((group) => group.split('').reverse().join(''))
      .join(' ') || '0'
  );
}

function formatBtcGroup(sats: number): string {
  const btc = sats / SATS_PER_BTC;
  const [whole, decimal = ''] = btc.toFixed(8).split('.');
  const paddedDecimal = decimal.padEnd(8, '0');
  return `${whole}.${paddedDecimal.slice(0, 2)} ${paddedDecimal
    .slice(2)
    .match(/.{1,3}/g)
    ?.join(' ')} BTC`.trim();
}

export default function satsComma(sats: number, format: SatcommaFormat = SatcommaFormat.SATS): string {
  if (!Number.isFinite(sats)) {
    throw new Error('Invalid input: sats must be a finite number');
  }

  if (sats < 0) {
    return `-${satsComma(Math.abs(sats), format)}`;
  }

  return format === SatcommaFormat.SATS ? formatSatsGroup(sats) : formatBtcGroup(sats);
}
