import type { Precondition } from './flow.js';

export type MaterialiserMetadata =
  | { readonly kind: 'exact'; readonly amount: bigint }
  | { readonly kind: 'exact-native'; readonly amount: bigint }
  // The program pulls at most `amount` and consumes the measured result;
  // `amount` is what an authoriser signs and what a spend report states, not
  // what was deposited. `min`, when present, is a floor the program asserts
  // on-chain right after the pull, so the deposit never lands below it.
  | { readonly kind: 'capped'; readonly amount: bigint; readonly min?: bigint }
  // The program pulls whatever the payer holds. `min`, when present, is a
  // floor the program asserts on-chain right after the sweep, and the floor
  // a compile may count on for the input.
  | { readonly kind: 'runtime'; readonly min?: bigint };

export interface MaterialiserResolution {
  readonly meta: MaterialiserMetadata;
  readonly preconditions: readonly Precondition[];
}

export const foldMaterialiserMetadata = <R>(
  meta: MaterialiserMetadata,
  cases: {
    readonly exact: (amount: bigint) => R;
    readonly exactNative: (amount: bigint) => R;
    readonly capped: (amount: bigint, min: bigint | undefined) => R;
    readonly runtime: (min: bigint | undefined) => R;
  },
): R => {
  if (meta.kind === 'exact') return cases.exact(meta.amount);
  if (meta.kind === 'exact-native') return cases.exactNative(meta.amount);
  if (meta.kind === 'capped') return cases.capped(meta.amount, meta.min);
  return cases.runtime(meta.min);
};
