import { NextResponse } from 'next/server'
import Stripe from 'stripe'
import { getProductBySlug, mediaUrl } from '@/lib/payload'

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

export async function POST(request: Request) {
  const body = await request.json().catch(() => ({}))
  const slug = body?.product as string | undefined
  const email = body?.email as string | undefined

  if (!slug) return NextResponse.json({ error: 'Produit manquant' }, { status: 400 })

  const product = await getProductBySlug(slug)
  if (!product || !product.price) {
    return NextResponse.json({ error: 'Produit non disponible' }, { status: 404 })
  }

  const img = (product.images?.[0] as { image: unknown } | undefined)?.image
  const baseUrl =
    process.env.NEXT_PUBLIC_SERVER_URL ?? `${new URL(request.url).origin}`
  const imgUrl = mediaUrl(img as never, 'feature')
  const absoluteImgUrl = imgUrl && imgUrl.startsWith('http') ? imgUrl : imgUrl ? `${baseUrl}${imgUrl}` : undefined

  try {
    // custom_text is supported at runtime on API versions >= 2022-11-15;
    // the stripe@10 SDK types don't know about it, so we cast the params.
    const params: Stripe.Checkout.SessionCreateParams = {
      mode: 'payment',
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: (product.currency || 'EUR').toLowerCase(),
            product_data: {
              name: product.productDisplayName,
              description: product.description?.substring(0, 500) || undefined,
              images: absoluteImgUrl ? [absoluteImgUrl] : [],
            },
            unit_amount: product.price,
          },
          quantity: 1,
        },
      ],
      metadata: { product: slug },
      success_url: `${baseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${baseUrl}/#collection`,
      locale: 'fr',
      customer_email: email || undefined,
    }
    ;(params as Stripe.Checkout.SessionCreateParams & { custom_text: unknown }).custom_text = {
      submit: { message: 'Pièce unique — fabriquée à Paris. Délai : 6 à 8 semaines.' },
    }
    const session = await stripe.checkout.sessions.create(params)

    return NextResponse.json({ url: session.url })
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Erreur Stripe'
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
