/**
 * config/stripe.js
 *
 * Stripe SDK singleton. The API version is pinned so that behaviour is
 * deterministic across deploys (Stripe upgrades its API version every
 * month; without a pin, your checkout/webhook logic could subtly
 * change when Stripe rolls out a backwards-compatible change).
 *
 * Override per-deploy via STRIPE_API_VERSION. Default = the current
 * stable version as of 2026-06 (dahlia release). Re-check
 * https://docs.stripe.com/api/versioning at every quarterly deploy and
 * bump here + test the billing flow end-to-end.
 */

'use strict';

const Stripe = require('stripe');

const DEFAULT_API_VERSION = '2026-06-24.dahlia';
const apiVersion = process.env.STRIPE_API_VERSION || DEFAULT_API_VERSION;

// Lazy-initialise the SDK instance. Previous version crashed at boot when
// STRIPE_SECRET_KEY was empty (it did `module.exports = null`, then tried
// to set DEFAULT_API_VERSION on null). Now: the real Stripe client is
// constructed on first property access, and only if STRIPE_SECRET_KEY
// is set. The export is a Proxy so call sites in routes/billing.js and
// routes/webhook.js can still write `stripe.customers.create(...)` without
// any code change — the Proxy forwards every non-metadata property to
// the lazily-built client.

let _instance = null;
function realClient() {
  if (!_instance) {
    if (!process.env.STRIPE_SECRET_KEY) {
      throw new Error('STRIPE_SECRET_KEY is not set. Add it to .env or the cPanel "Setup Node.js App" environment editor, then restart.');
    }
    _instance = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion });
  }
  return _instance;
}

const meta = { DEFAULT_API_VERSION, apiVersion };

module.exports = new Proxy(meta, {
  get(target, prop) {
    if (prop in target) return target[prop];
    return realClient()[prop];
  },
  has(target, prop) {
    return prop in target || true; // every Stripe method is "available"
  },
});
