import Stripe from 'stripe'

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const stripeSecretKey = config.stripeSecretKey

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

  const params = event.context.params as { sessionId?: string }
  const sessionId = params?.sessionId

  if (!sessionId) {
    throw createError({ statusCode: 400, statusMessage: 'Missing session id' })
  }

  const stripe = new Stripe(stripeSecretKey, {
    apiVersion: '2025-10-29.clover',
  })

  try {
    const session = await stripe.checkout.sessions.retrieve(sessionId, {
      expand: ['payment_intent', 'customer'],
    })

    const customerDetails = session.customer_details ?? null

    return {
      id: session.id,
      paymentStatus: session.payment_status,
      amountTotal: session.amount_total,
      currency: session.currency,
      customerEmail: customerDetails?.email ?? session.customer_email ?? null,
      customerName: customerDetails?.name ?? null,
      createdAt: session.created ? new Date(session.created * 1000).toISOString() : null,
      metadata: session.metadata ?? {},
      customerDetails: customerDetails
        ? {
            name: customerDetails.name ?? null,
            email: customerDetails.email ?? null,
            phone: customerDetails.phone ?? null,
            address: customerDetails.address
              ? {
                  line1: customerDetails.address.line1 ?? null,
                  line2: customerDetails.address.line2 ?? null,
                  city: customerDetails.address.city ?? null,
                  state: customerDetails.address.state ?? null,
                  postalCode: customerDetails.address.postal_code ?? null,
                  country: customerDetails.address.country ?? null,
                }
              : null,
          }
        : null,
    }
  } catch (error: any) {
    throw createError({
      statusCode: error?.statusCode ?? 500,
      statusMessage: error?.message ?? 'Unable to retrieve checkout session',
    })
  }
})
