import { NextRequest, NextResponse } from 'next/server'
import Stripe from 'stripe'
import { prisma } from '@/lib/prisma'
import { stripe } from '@/lib/stripe'
import { generateOrderNumber } from '@/lib/orderNumber'

const PRODUCT_NAMES: Record<string, string> = {
  samarreta: 'Samarreta Cursa de la Cirera 2026',
  mitjons: 'Mitjons Cursa de la Cirera 2026',
  pack: 'Pack Samarreta + Mitjons Cursa de la Cirera 2026',
}

const PRODUCT_PRICES: Record<string, number> = {
  samarreta: 1000,
  mitjons: 1000,
  pack: 1850,
}

const SHIPPING_PRICE = 799

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const {
      product, sizeTshirt, sizeSocks, shipping,
      nom, cognoms, telefon, email,
      adreca, codiPostal, poblacio, provincia,
    } = body

    // Validate product
    if (!product || !PRODUCT_PRICES[product]) {
      return NextResponse.json({ error: 'Producte no vàlid' }, { status: 400 })
    }
    if (!['correos', 'recollida'].includes(shipping)) {
      return NextResponse.json({ error: 'Mètode de lliurament no vàlid' }, { status: 400 })
    }
    if (!nom || !cognoms || !telefon || !email) {
      return NextResponse.json({ error: 'Falten dades obligatòries' }, { status: 400 })
    }

    const baseAmountCents = PRODUCT_PRICES[product]
    const shippingAmountCents = shipping === 'correos' ? SHIPPING_PRICE : 0
    const totalCents = baseAmountCents + shippingAmountCents

    const orderNumber = await generateOrderNumber()

    // Build Stripe line items
    const lineItems: Stripe.Checkout.SessionCreateParams.LineItem[] = [
      {
        price_data: {
          currency: 'eur',
          product_data: {
            name: PRODUCT_NAMES[product],
            description: [
              sizeTshirt ? `Samarreta talla ${sizeTshirt}` : '',
              sizeSocks ? `Mitjons talla ${sizeSocks}` : '',
            ]
              .filter(Boolean)
              .join(' · ') || undefined,
            images: [],
          },
          unit_amount: baseAmountCents,
        },
        quantity: 1,
      },
    ]

    if (shippingAmountCents > 0) {
      lineItems.push({
        price_data: {
          currency: 'eur',
          product_data: { name: 'Enviament Correos Express' },
          unit_amount: shippingAmountCents,
        },
        quantity: 1,
      })
    }

    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ?? 'http://localhost:3000'

    // Create Stripe checkout session first to get the session ID
    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      line_items: lineItems,
      customer_email: email,
      locale: 'es',
      success_url: `${baseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${baseUrl}/?cancelled=true`,
      metadata: { orderNumber },
      payment_intent_data: {
        description: `${orderNumber} – ${PRODUCT_NAMES[product]}`,
      },
    })

    // Create order in DB
    await prisma.order.create({
      data: {
        orderNumber,
        product,
        sizeTshirt: sizeTshirt ?? null,
        sizeSocks: sizeSocks ?? null,
        baseAmount: baseAmountCents / 100,
        shippingAmount: shippingAmountCents / 100,
        totalAmount: totalCents / 100,
        nom,
        cognoms,
        telefon,
        email,
        adreca: adreca ?? null,
        codiPostal: codiPostal ?? null,
        poblacio: poblacio ?? null,
        provincia: provincia ?? null,
        shipping,
        stripeSessionId: session.id,
        status: 'PENDING',
      },
    })

    return NextResponse.json({ url: session.url })
  } catch (err) {
    console.error('[checkout]', err)
    return NextResponse.json(
      { error: 'Error intern. Torna-ho a intentar.' },
      { status: 500 }
    )
  }
}
