import { NextResponse } from 'next/server'
import Stripe from 'stripe'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY ?? '', {
  apiVersion: '2022-08-01',
})

export async function GET(_request: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params
  try {
    const session = await stripe.checkout.sessions.retrieve(id, {
      expand: ['payment_intent.latest_charge'],
    })
    // latest_charge was added in API version 2022-11-15; stripe@10 types omit it.
    const paymentIntent = session.payment_intent as (Stripe.PaymentIntent & { latest_charge?: Stripe.Charge | string | null }) | null
    const charge =
      paymentIntent?.latest_charge && typeof paymentIntent.latest_charge === 'object'
        ? paymentIntent.latest_charge
        : null
    return NextResponse.json({
      status: session.payment_status,
      amount: session.amount_total,
      currency: session.currency,
      customer_email: session.customer_details?.email ?? null,
      product: session.metadata?.product ?? null,
      receipt_url: charge?.receipt_url ?? null,
    })
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Erreur session'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
