import Stripe from 'stripe'
import { prisma } from '@/lib/db'

let stripeInstance: Stripe | null = null

export async function getStripeConfig(): Promise<{ secretKey: string; publicKey: string; webhookSecret: string } | null> {
  try {
    const keys = await (prisma as any).systemSetting.findMany({
      where: {
        key: { in: ['stripe_secret_key', 'stripe_public_key', 'stripe_webhook_secret'] },
      },
    })

    const secretKey = keys.find((k: any) => k.key === 'stripe_secret_key')?.value
    const publicKey = keys.find((k: any) => k.key === 'stripe_public_key')?.value
    const webhookSecret = keys.find((k: any) => k.key === 'stripe_webhook_secret')?.value

    if (!secretKey || !publicKey) {
      console.log('[Stripe] Config missing:', { hasSecret: !!secretKey, hasPublic: !!publicKey, keysFound: keys.length })
      return null
    }

    return { secretKey, publicKey, webhookSecret: webhookSecret || '' }
  } catch (error) {
    console.error('[Stripe] Error loading config:', error)
    return null
  }
}

export async function getStripe(): Promise<Stripe | null> {
  const config = await getStripeConfig()
  if (!config) return null

  if (!stripeInstance || (stripeInstance as any)._api?.auth !== config.secretKey) {
    stripeInstance = new Stripe(config.secretKey, {
      apiVersion: '2024-06-20' as any,
    })
  }

  return stripeInstance
}

export async function saveStripeConfig(config: {
  secretKey?: string
  publicKey?: string
  webhookSecret?: string
}) {
  const entries = [
    { key: 'stripe_secret_key', value: config.secretKey, isSecret: true },
    { key: 'stripe_public_key', value: config.publicKey, isSecret: false },
    { key: 'stripe_webhook_secret', value: config.webhookSecret, isSecret: true },
  ].filter(e => e.value !== undefined && e.value !== '••••••••')

  for (const entry of entries) {
    await (prisma as any).systemSetting.upsert({
      where: { key: entry.key },
      update: { value: entry.value },
      create: { key: entry.key, value: entry.value, isSecret: entry.isSecret, category: 'stripe' },
    })
  }
}
