import Stripe from 'stripe';
import type { MultidealEnv } from '../../env.js';

let cached: Stripe | null = null;

export function getStripe(
  env: Pick<MultidealEnv, 'STRIPE_SECRET_KEY' | 'STRIPE_API_VERSION'>,
): Stripe {
  if (cached) return cached;
  if (!env.STRIPE_SECRET_KEY) throw new Error('STRIPE_SECRET_KEY not set');
  cached = new Stripe(env.STRIPE_SECRET_KEY, {
    // Cast to the pinned version literal — LatestApiVersion in stripe@22 = typeof ApiVersion = '2026-04-22.dahlia'.
    // The Stripe namespace doesn't re-export LatestApiVersion so we cast to the equivalent literal type.
    apiVersion: (env.STRIPE_API_VERSION ?? '2026-04-22.dahlia') as '2026-04-22.dahlia',
    typescript: true,
    maxNetworkRetries: 2,
    timeout: 20_000,
  });
  return cached;
}

// Reset cache for tests + after env rotation
export function resetStripeClient(): void {
  cached = null;
}
