import { describe, expect, it } from 'vitest'
import { buildChargeKey, parseOrderId } from './charge-key.js'
import { CheckoutValidationError, isCheckoutValidationError } from './errors.js'

describe('chargekey-roundtrip', () => {
  it('parseOrderId(buildChargeKey(uuid)) === uuid', () => {
    const orderId = 'a1b2c3d4-e5f6-4789-a012-3456789abcde'
    expect(parseOrderId(buildChargeKey(orderId))).toBe(orderId)
  })

  it('malformed key (bad prefix) → CheckoutValidationError', () => {
    expect(() => parseOrderId('refund:a1b2c3d4-e5f6-4789-a012-3456789abcde')).toThrow(
      CheckoutValidationError,
    )
    try {
      parseOrderId('refund:a1b2c3d4-e5f6-4789-a012-3456789abcde')
    } catch (e) {
      expect(isCheckoutValidationError(e)).toBe(true)
      if (isCheckoutValidationError(e)) {
        expect(e.reason).toBe('INVALID_CHARGE_KEY')
        expect(e.httpStatus).toBe(400)
      }
    }
  })

  it('malformed key (non-uuid remainder) → CheckoutValidationError', () => {
    expect(() => parseOrderId(buildChargeKey('not-a-uuid'))).toThrow(CheckoutValidationError)
    try {
      parseOrderId('charge:not-a-uuid')
    } catch (e) {
      expect(isCheckoutValidationError(e)).toBe(true)
      if (isCheckoutValidationError(e)) {
        expect(e.reason).toBe('INVALID_CHARGE_KEY')
      }
    }
  })
})
