import type { Stripe } from '@stripe/stripe-js';

const stripePromiseCache = new Map<string, Promise<Stripe | null>>();

export async function getStripe(publishableKey?: string): Promise<Stripe | null> {
  if (!publishableKey) {
    return null;
  }

  if (!stripePromiseCache.has(publishableKey)) {
    const promise = import('@stripe/stripe-js').then(({ loadStripe }) => loadStripe(publishableKey));
    stripePromiseCache.set(publishableKey, promise);
  }

  return stripePromiseCache.get(publishableKey) ?? null;
}

export function clearStripeCache(): void {
  stripePromiseCache.clear();
}

