import Stripe from 'stripe'

export interface CreateCheckoutSessionParams {
  customerId: string
  priceId: string
  organizationId: string
}

// Lazy initialization to avoid calling useRuntimeConfig at module import time
let stripeInstance: Stripe | null = null

function getStripe(): Stripe {
  if (!stripeInstance) {
    const config = useRuntimeConfig()
    const secretKey = config.stripeSecretKey

    if (!secretKey) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Stripe secret key not configured'
      })
    }

    stripeInstance = new Stripe(secretKey, {
      apiVersion: '2025-11-17.clover'
    })
  }

  return stripeInstance
}

export const stripeService = {
  async createCustomer(organizationId: string, email: string) {
    try {
      const stripe = getStripe()
      const customer = await stripe.customers.create({
        email,
        metadata: { organizationId }
      })
      return customer.id
    } catch (error) {
      console.error('[StripeService] Error creating customer:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to create customer'
      })
    }
  },

  async createCheckoutSession({
    customerId,
    priceId,
    organizationId
  }: CreateCheckoutSessionParams) {
    try {
      const stripe = getStripe()
      const config = useRuntimeConfig()
      const baseUrl = config.public.betterAuthUrl || 'http://localhost:3000'

      const session = await stripe.checkout.sessions.create({
        customer: customerId,
        billing_address_collection: 'required',
        customer_update: {
          address: 'auto'
        },
        allow_promotion_codes: true,
        success_url: `${baseUrl}/dashboard/billing?success=true`,
        cancel_url: `${baseUrl}/dashboard/billing?cancel=true`,
        line_items: [
          {
            price: priceId,
            quantity: 1
          }
        ],
        mode: 'subscription',
        metadata: {
          organizationId
        }
      })
      return session
    } catch (error) {
      console.error('[StripeService] Error creating checkout session:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to create checkout session'
      })
    }
  },

  async getCheckoutSession(sessionId: string) {
    try {
      const stripe = getStripe()
      const session = await stripe.checkout.sessions.retrieve(sessionId)
      return session
    } catch (error) {
      console.error('[StripeService] Error getting checkout session:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to get checkout session'
      })
    }
  },

  async getSubscription(subscriptionId: string) {
    try {
      const stripe = getStripe()
      const subscription = await stripe.subscriptions.retrieve(subscriptionId)
      return subscription
    } catch (error) {
      console.error('[StripeService] Error getting subscription:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to get subscription'
      })
    }
  },

  async createBillingPortalSession(customerId: string) {
    try {
      const stripe = getStripe()
      const config = useRuntimeConfig()
      const baseUrl = config.public.betterAuthUrl || 'http://localhost:3000'

      const session = await stripe.billingPortal.sessions.create({
        customer: customerId,
        return_url: `${baseUrl}/dashboard/billing`
      })
      return session
    } catch (error) {
      console.error('[StripeService] Error creating billing portal session:', error)
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to create billing portal session'
      })
    }
  }
}
