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' });
}

/**
 * Resolve the active Stripe secret key using this priority:
 * 1. Mode-aware DB lookup (DB mode always takes precedence):
 *    a. If stripe_mode is explicitly set → use the corresponding bucket only (strict)
 *    b. If stripe_mode is NOT set yet (pre-migration):
 *       - If only test bucket has a key → use test key
 *       - If only live bucket has a key → use live key
 *    c. Pre-migration legacy key (stripe_secret_key) when no bucketed keys exist
 * 2. STRIPE_SECRET_KEY env var — fallback only when no DB key of any kind is configured.
 *    Setting the env var does NOT override DB mode; it only applies when the DB has
 *    no Stripe keys at all (e.g. a fresh deployment before admin has saved any keys).
 */
async function resolveStripeSecretKey(): Promise<{ key: string; mode: 'test' | 'live' | 'env' } | null> {
  const { getPlatformSettings } = await import('@server/services/admin.service');
  const settings = await getPlatformSettings();

  const modeExplicit = settings.stripe_mode as 'test' | 'live' | undefined;
  const testKey = settings.stripe_test_secret_key as string | undefined;
  const liveKey = settings.stripe_live_secret_key as string | undefined;
  const legacyKey = settings.stripe_secret_key as string | undefined;

  if (modeExplicit) {
    // Strict: only use the bucket matching the explicit mode
    const modeKey = modeExplicit === 'test' ? testKey : liveKey;
    if (modeKey) return { key: modeKey, mode: modeExplicit };
    // Mode explicitly set but bucket empty — do not fall through to env
    return null;
  }

  // Mode not yet set: infer from available bucket keys
  if (testKey && !liveKey) return { key: testKey, mode: 'test' };
  if (liveKey && !testKey) return { key: liveKey, mode: 'live' };
  if (liveKey) return { key: liveKey, mode: 'live' };

  // Pre-migration fallback: legacy single-key field
  if (legacyKey) return { key: legacyKey, mode: legacyKey.startsWith('sk_test_') ? 'test' : 'live' };

  // Last resort: env var (no DB keys configured at all)
  const envKey = process.env.STRIPE_SECRET_KEY;
  if (envKey) return { key: envKey, mode: envKey.startsWith('sk_test_') ? 'test' : 'live' };

  return null;
}

async function getStripeClientFromDb(): Promise<Stripe> {
  const resolved = await resolveStripeSecretKey();
  if (!resolved) {
    throw new Error('Stripe is not configured. Add a Stripe secret key in Platform Keys.');
  }
  return new Stripe(resolved.key, { apiVersion: '2026-03-25.dahlia' });
}

async function getStripeSecretKey(): Promise<string | null> {
  try {
    const resolved = await resolveStripeSecretKey();
    return resolved?.key ?? null;
  } catch {
    return null;
  }
}

export { getStripeClient, getStripeClientFromDb, getStripeSecretKey };
