import { PaymentProviderError } from './errors'

const PUBLISHABLE_KEY = /^pk_(test|live)_[A-Za-z0-9]+$/
const CLIENT_SECRET = /^(pi|seti)_[A-Za-z0-9]+_secret_[A-Za-z0-9]+$/

/**
 * ALLOWLIST / default-deny: throw unless the key is a Stripe publishable key.
 * NEVER a denylist (reject sk_/rk_, else accept) — an unenumerated secret prefix would leak.
 */
export function assertPublishableKey(key: string): void {
  if (!PUBLISHABLE_KEY.test(key)) {
    throw new PaymentProviderError(
      'billing-react: publishableKey must be a Stripe publishable key (pk_test_… / pk_live_…). ' +
        'Refusing to mount — a secret/restricted key in the browser is a catastrophic leak.',
    )
  }
}

/** Fail closed on a malformed PaymentIntent/SetupIntent client secret — never mount Elements with a bad secret. */
export function assertClientSecretShape(clientSecret: string): void {
  if (!CLIENT_SECRET.test(clientSecret)) {
    throw new PaymentProviderError('billing-react: clientSecret is malformed (expected pi_…_secret_… / seti_…_secret_…).')
  }
}