import { NextRequest, NextResponse } from 'next/server'
import { getStripe } from '@/lib/stripe'

export const dynamic = 'force-dynamic'

export async function POST(req: NextRequest) {
  try {
    const { amount, name, message } = await req.json()

    if (!amount || amount < 1 || amount > 1000) {
      return NextResponse.json({ error: 'Ungültiger Betrag' }, { status: 400 })
    }

    const stripe = await getStripe()
    if (!stripe) {
      return NextResponse.json({ error: 'Stripe ist nicht konfiguriert. Bitte kontaktiere den Administrator.' }, { status: 503 })
    }

    const amountInCents = Math.round(amount * 100)

    const origin = req.headers.get('origin') || req.nextUrl.origin

    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      line_items: [
        {
          price_data: {
            currency: 'chf',
            product_data: {
              name: 'Spende für Lageplan',
              description: `Freiwillige Spende von CHF ${amount} für die Weiterentwicklung`,
            },
            unit_amount: amountInCents,
          },
          quantity: 1,
        },
      ],
      metadata: {
        donor_name: name || 'Anonym',
        donor_message: message || '',
        type: 'donation',
      },
      success_url: `${origin}/spenden/danke?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${origin}/spenden`,
    })

    return NextResponse.json({ url: session.url })
  } catch (error) {
    console.error('Stripe checkout error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Checkout fehlgeschlagen' },
      { status: 500 }
    )
  }
}
