import Stripe from 'stripe';
import { prisma } from '../config/database';
import { decrypt } from '../utils/crypto';
import { logger } from '../utils/logger';

let _stripe: Stripe | null = null;

/** Get (or lazily create) the Stripe client, reading keys from PaymentSettings */
export async function getStripe(): Promise<Stripe> {
  if (_stripe) return _stripe;

  const settings = await prisma.paymentSettings.findFirst();
  if (!settings) {
    throw new Error('Payment settings not configured — set Stripe keys in admin settings');
  }

  const secretKey = decrypt(settings.stripeSecretKey);
  if (!secretKey) {
    throw new Error('Stripe secret key not configured — set it in admin payment settings');
  }

  _stripe = new Stripe(secretKey, { apiVersion: '2026-01-28.clover' });

  logger.info('Stripe client initialized');
  return _stripe;
}

/** Force re-initialization after settings change */
export function resetStripeClient(): void {
  _stripe = null;
}

/** Get the publishable key (for public config endpoint) */
export async function getPublishableKey(): Promise<string> {
  const settings = await prisma.paymentSettings.findFirst();
  return settings?.stripePublishableKey || '';
}

/** Get the webhook secret (decrypted) */
export async function getWebhookSecret(): Promise<string> {
  const settings = await prisma.paymentSettings.findFirst();
  if (!settings?.stripeWebhookSecret) return '';
  return decrypt(settings.stripeWebhookSecret);
}
