import { describe, expect, it } from 'vitest'
import { applyToCart } from './apply.js'
import { createMemoryCartStore } from './testing.js'
import type { PriceSnapshot } from './types.js'

const usdPrice = (amount: bigint): PriceSnapshot => ({
  amount,
  currency: 'USD',
  priceMode: 'inclusive',
})

describe('applyToCart', () => {
  it('roundtrips addLine through the store', async () => {
    const store = createMemoryCartStore()
    const cartId = 'cart-roundtrip'

    const saved = await applyToCart(store, cartId, {
      type: 'addLine',
      variantId: 'variant-a',
      qty: 2,
      price: usdPrice(1500n),
    })

    const loaded = await store.load(cartId)
    expect(loaded).toEqual(saved)
    expect(loaded?.lines).toHaveLength(1)
    expect(loaded?.subtotal).toBe(3000n)
  })

  it('creates a missing cart on first apply', async () => {
    const store = createMemoryCartStore()
    const cartId = 'cart-new'

    expect(await store.load(cartId)).toBeNull()

    const cart = await applyToCart(store, cartId, {
      type: 'addLine',
      variantId: 'variant-a',
      qty: 1,
      price: usdPrice(1000n),
    })

    expect(cart.id).toBe(cartId)
    expect(cart.lines).toHaveLength(1)
    expect(await store.load(cartId)).toEqual(cart)
  })
})
