import Stripe from 'stripe';

/**
 * Stripe payment gateway — enabled only when keys are configured AND not
 * explicitly switched off:
 *
 *   STRIPE_SECRET_KEY=sk_test_...      (required to enable)
 *   STRIPE_PUBLISHABLE_KEY=pk_test_... (required to enable)
 *   STRIPE_ENABLED=false               (kill switch — back to the mock gateway)
 *
 * When disabled, checkout falls back to the built-in mock gateway exactly as
 * before, so the app keeps working without Stripe.
 */

export type PaymentGateway = 'stripe' | 'mock';

export function stripeEnabled(): boolean {
  if (String(process.env.STRIPE_ENABLED || 'true').toLowerCase() === 'false') return false;
  return Boolean(process.env.STRIPE_SECRET_KEY && process.env.STRIPE_PUBLISHABLE_KEY);
}

export function paymentGateway(): PaymentGateway {
  return stripeEnabled() ? 'stripe' : 'mock';
}

export function publishableKey(): string {
  return process.env.STRIPE_PUBLISHABLE_KEY || '';
}

let client: Stripe | null = null;

export function getStripe(): Stripe {
  if (!client) {
    client = new Stripe(process.env.STRIPE_SECRET_KEY as string);
  }
  return client;
}

export function webhookSecret(): string {
  return process.env.STRIPE_WEBHOOK_SECRET || '';
}

/** Human-readable status for /api/health. */
export function getStripeStatus(): { gateway: PaymentGateway; reason?: string } {
  if (stripeEnabled()) return { gateway: 'stripe' };
  const reason =
    String(process.env.STRIPE_ENABLED || '').toLowerCase() === 'false'
      ? 'STRIPE_ENABLED=false — mock gateway in use.'
      : 'STRIPE_SECRET_KEY / STRIPE_PUBLISHABLE_KEY not set — mock gateway in use.';
  return { gateway: 'mock', reason };
}
