/**
 * Money handling utilities
 * All amounts are stored in integer cents to avoid floating-point precision issues
 */

export class Money {
  /**
   * Convert decimal amount to cents (integer)
   * @param amount - Decimal amount (e.g., 99.99)
   * @returns Integer cents (e.g., 9999)
   */
  static toCents(amount: number): number {
    return Math.round(amount * 100)
  }

  /**
   * Convert cents to decimal amount
   * @param cents - Integer cents (e.g., 9999)
   * @returns Decimal amount (e.g., 99.99)
   */
  static fromCents(cents: number): number {
    return cents / 100
  }

  /**
   * Format cents as currency string
   * @param cents - Integer cents
   * @param currency - Currency code (e.g., 'USD')
   * @param locale - Locale for formatting (default: 'en-US')
   */
  static format(cents: number, currency = "USD", locale = "en-US"): string {
    return new Intl.NumberFormat(locale, {
      style: "currency",
      currency,
    }).format(this.fromCents(cents))
  }

  /**
   * Validate that two amounts match exactly
   * @param amount1 - First amount in cents
   * @param amount2 - Second amount in cents
   * @throws Error if amounts don't match
   */
  static validateMatch(amount1: number, amount2: number): void {
    if (amount1 !== amount2) {
      throw new Error(`Amount mismatch: ${amount1} cents !== ${amount2} cents`)
    }
  }

  /**
   * Ensure amount is a valid positive integer
   */
  static validate(cents: number): boolean {
    return Number.isInteger(cents) && cents > 0
  }
}
