import { describe, expect, it } from 'vitest'
import {
  CheckoutProviderError,
  CheckoutWireError,
  isCheckoutProviderError,
  isCheckoutWireError,
  isCheckoutValidationError,
  isOrderIdempotencyConflictError,
  isPaymentConfirmError,
} from './errors.js'
import type { StaleSplit } from '@platform-modules/commerce-checkout'

describe('CheckoutWireError', () => {
  it('carries an optional revived stale split', () => {
    const stale: StaleSplit = { removed: ['v1'], updated: [{ variantId: 'v2', was: 100n, now: 120n }] }
    const e = new CheckoutWireError('stale items', { stale })
    expect(e.name).toBe('CheckoutWireError')
    expect(e.stale).toEqual(stale)
    expect(isCheckoutWireError(e)).toBe(true)
  })

  it('guard is structural — name + code, instanceof not required', () => {
    expect(isCheckoutWireError(new CheckoutWireError('x'))).toBe(true)
    expect(isCheckoutWireError({ name: 'CheckoutWireError', code: 'CHECKOUT_WIRE' })).toBe(true)
    expect(isCheckoutWireError({ name: 'CheckoutWireError' })).toBe(false)
    expect(isCheckoutWireError(new Error('x'))).toBe(false)
    expect(isCheckoutWireError(null)).toBe(false)
  })
})

describe('CheckoutProviderError', () => {
  it('names the hook used outside the provider', () => {
    const e = new CheckoutProviderError('useCheckout')
    expect(e.message).toContain('useCheckout')
    expect(isCheckoutProviderError(e)).toBe(true)
  })
})

describe('re-exported core + billing-react guards', () => {
  it('exposes the guards consumers branch on', () => {
    expect(typeof isCheckoutValidationError).toBe('function')
    expect(typeof isOrderIdempotencyConflictError).toBe('function')
    expect(typeof isPaymentConfirmError).toBe('function')
  })
})