import { idempotencyKey } from '@platform-modules/billing'
import { CheckoutValidationError } from './errors.js'

const UUID_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i

export function buildChargeKey(orderId: string): string {
  return idempotencyKey(['charge', orderId])
}

export function parseOrderId(chargeKey: string): string {
  const separator = chargeKey.indexOf(':')
  if (separator === -1) {
    throw new CheckoutValidationError('INVALID_CHARGE_KEY')
  }

  const prefix = chargeKey.slice(0, separator)
  if (prefix !== 'charge') {
    throw new CheckoutValidationError('INVALID_CHARGE_KEY')
  }

  const encoded = chargeKey.slice(separator + 1)
  let orderId: string
  try {
    orderId = decodeURIComponent(encoded)
  } catch {
    throw new CheckoutValidationError('INVALID_CHARGE_KEY')
  }

  if (!UUID_RE.test(orderId)) {
    throw new CheckoutValidationError('INVALID_CHARGE_KEY')
  }

  return orderId
}
