import { OrderIntegrityError } from './errors.js'
import type { NewOrderLine, NewVendorSplit } from './types.js'

export function assertOrderIntegrity(o: {
  subtotal: bigint
  tax: bigint
  discount: bigint
  total: bigint
  lines: Pick<NewOrderLine, 'lineTotal'>[]
  splits: Pick<NewVendorSplit, 'amount'>[]
}): void {
  let lineSum = 0n
  for (const line of o.lines) {
    lineSum += line.lineTotal
  }
  if (lineSum !== o.subtotal) {
    throw new OrderIntegrityError('lines')
  }

  if (o.subtotal + o.tax - o.discount !== o.total) {
    throw new OrderIntegrityError('total')
  }

  let splitSum = 0n
  for (const split of o.splits) {
    splitSum += split.amount
  }
  if (splitSum !== o.total) {
    throw new OrderIntegrityError('splits')
  }
}
