// Generated by bynkc — do not edit by hand.
// commons commerce.money

import { Ok, Err, Some, None, type Result, type Option, type ValidationError } from "../runtime.js";

import { Duration } from "../chrono/time/duration.js";
import { Timestamp } from "../chrono/time/timestamp.js";

/**
 * Money commons. Represents currency amounts as minor units (pence, cents)
 * paired with currency codes. Supports basic arithmetic with currency-mismatch
 * detection.
 */

export type CurrencyCode = string & { readonly __brand: "CurrencyCode" };

export const CurrencyCode = {
  of(value: string): Result<CurrencyCode, ValidationError> {
    if (!new RegExp("^" + "[A-Z]{3}" + "$").test(value)) {
      return Err({ field: "CurrencyCode", message: "must match /[A-Z]{3}/", value });
    }
    return Ok(value as CurrencyCode);
  },
  unsafe(value: string): CurrencyCode {
    return value as CurrencyCode;
  },
};

/**
 * A monetary amount paired with its currency.
 */
export interface Money {
  readonly minorUnits: number;
  readonly currency: CurrencyCode;
}

export const Money = {
  zero(currency: CurrencyCode): Money {
    return { minorUnits: 0, currency };
  },
  add(self: Money, other: Money): Result<Money, MoneyError> {
    return (self.currency !== other.currency ? Err(MoneyError.CurrencyMismatch) : Ok({ minorUnits: self.minorUnits + other.minorUnits, currency: self.currency }));
  },
};

export type MoneyError =
    { readonly tag: "CurrencyMismatch" }
  | { readonly tag: "InsufficientFunds" };

export const MoneyError = {
  CurrencyMismatch: { tag: "CurrencyMismatch" } as MoneyError,
  InsufficientFunds: { tag: "InsufficientFunds" } as MoneyError,
};

/**
 * A transaction record pairing money movement with its timestamp.
 * The timestamp uses chrono.time's opaque Timestamp type, ensuring temporal
 * operations are explicit.
 */
export interface Transaction {
  readonly amount: Money;
  readonly occurred: Timestamp;
}

export const Transaction = {
  of(amount: Money, occurred: Timestamp): Transaction {
    return { amount, occurred };
  },
  duration(self: Transaction, other: Transaction): Duration {
    return Timestamp.diff(self.occurred, other.occurred);
  },
};

