import Stripe from 'stripe';

function getStripeClient(): Stripe {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key) {
    throw new Error('STRIPE_SECRET_KEY is not configured. Please add your Stripe secret key to environment variables.');
  }
  return new Stripe(key, { apiVersion: '2026-03-25.dahlia' });
}

async function getStripeClientFromDb(): Promise<Stripe> {
  const envKey = process.env.STRIPE_SECRET_KEY;
  if (envKey) {
    return new Stripe(envKey, { apiVersion: '2026-03-25.dahlia' });
  }
  const { getPlatformSettings } = await import('@server/services/admin.service');
  const settings = await getPlatformSettings();
  const dbKey = settings.stripe_secret_key as string | undefined;
  if (!dbKey) {
    throw new Error('Stripe is not configured. Set STRIPE_SECRET_KEY or add a Stripe Secret Key in Platform Keys.');
  }
  return new Stripe(dbKey, { apiVersion: '2026-03-25.dahlia' });
}

async function getStripeSecretKey(): Promise<string | null> {
  const envKey = process.env.STRIPE_SECRET_KEY;
  if (envKey) return envKey;
  try {
    const { getPlatformSettings } = await import('@server/services/admin.service');
    const settings = await getPlatformSettings();
    return (settings.stripe_secret_key as string | undefined) ?? null;
  } catch {
    return null;
  }
}

export { getStripeClient, getStripeClientFromDb, getStripeSecretKey };
