import { describe, expect, it } from 'vitest'
import { isNoPriceForCurrencyError, NoPriceForCurrencyError } from './errors.js'
import { resolvePrice } from './prices.js'
import type { Variant } from './types.js'

function variant(prices: Variant['prices']): Variant {
  return {
    id: '00000000-0000-4000-8000-000000000001',
    productId: '00000000-0000-4000-8000-000000000002',
    sku: 'SKU-1',
    attributes: {},
    prices,
  }
}

describe('resolvePrice', () => {
  it('returns the matching VariantPrice for a present currency', () => {
    const v = variant([{ currency: 'USD', amount: 1999n, priceMode: 'exclusive' }])
    expect(resolvePrice(v, 'USD')).toEqual({ currency: 'USD', amount: 1999n, priceMode: 'exclusive' })
  })

  it('throws NoPriceForCurrencyError when the currency is absent', () => {
    const v = variant([{ currency: 'USD', amount: 100n, priceMode: 'inclusive' }])
    expect(() => resolvePrice(v, 'EUR')).toThrow(NoPriceForCurrencyError)
    try {
      resolvePrice(v, 'EUR')
    } catch (e) {
      expect(isNoPriceForCurrencyError(e)).toBe(true)
      expect((e as NoPriceForCurrencyError).currency).toBe('EUR')
    }
  })

  it('resolves each currency on a multi-currency variant', () => {
    const v = variant([
      { currency: 'USD', amount: 1000n, priceMode: 'exclusive' },
      { currency: 'ILS', amount: 3500n, priceMode: 'inclusive' },
      { currency: 'EUR', amount: 900n, priceMode: 'exclusive' },
    ])
    expect(resolvePrice(v, 'USD').amount).toBe(1000n)
    expect(resolvePrice(v, 'ILS').priceMode).toBe('inclusive')
    expect(resolvePrice(v, 'EUR').currency).toBe('EUR')
  })

  it('throws NoPriceForCurrencyError when prices is empty', () => {
    expect(() => resolvePrice(variant([]), 'USD')).toThrow(NoPriceForCurrencyError)
  })
})
