/**
 * Pricing constants and calculation logic
 * Single source of truth for tax, shipping, and total calculations.
 * Used by both server (WooCommerce.normalize, payment-intent API)
 * and client (use-checkout-data hook).
 */

/** Sales tax rate applied to product subtotal (not shipping) */
export const TAX_RATE = 0.0725

/** Subtotal threshold (in cents) at or above which shipping is free */
export const FREE_SHIPPING_THRESHOLD_CENTS = 30000 // $300.00

export interface PricingBreakdown {
  /** Sum of line item totals, in cents */
  subtotal_cents: number
  /** Shipping cost after free-shipping rule, in cents */
  shipping_cents: number
  /** Original shipping cost before free-shipping discount, in cents */
  original_shipping_cents: number
  /** Calculated tax, in cents */
  tax_cents: number
  /** Grand total = subtotal + shipping + tax, in cents */
  total_cents: number
}

/**
 * Calculate the full pricing breakdown from line items and raw shipping cost.
 *
 * @param itemTotalsCents - Array of per-line-item total prices in cents
 *                          (each already quantity-adjusted, i.e. item.total * 100)
 * @param rawShippingCents - Shipping cost in cents from WooCommerce shipping_lines
 * @returns Complete pricing breakdown with all components
 */
export function calculatePricing(
  itemTotalsCents: number[],
  rawShippingCents: number,
): PricingBreakdown {
  const subtotal_cents = itemTotalsCents.reduce((sum, c) => sum + c, 0)

  const original_shipping_cents = rawShippingCents
  const shipping_cents =
    subtotal_cents >= FREE_SHIPPING_THRESHOLD_CENTS ? 0 : rawShippingCents

  // Tax is applied to product subtotal only, not shipping
  const tax_cents = Math.round(subtotal_cents * TAX_RATE)

  const total_cents = subtotal_cents + shipping_cents + tax_cents

  return {
    subtotal_cents,
    shipping_cents,
    original_shipping_cents,
    tax_cents,
    total_cents,
  }
}
