import { NextRequest, NextResponse } from 'next/server'
import { stripe } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'
import {
  sendOrderConfirmationToClient,
  sendNewOrderNotificationToAdmin,
} from '@/lib/email'
import { appendOrderToSheet } from '@/lib/sheets'

// Required: raw body for Stripe signature verification
export const dynamic = 'force-dynamic'

export async function POST(req: NextRequest) {
  const payload = await req.text()
  const sig = req.headers.get('stripe-signature')

  if (!sig) {
    return NextResponse.json({ error: 'No signature' }, { status: 400 })
  }

  let event: ReturnType<typeof stripe.webhooks.constructEvent>

  try {
    event = stripe.webhooks.constructEvent(
      payload,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET!
    )
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : 'Webhook error'
    console.error('[webhook] Signature verification failed:', msg)
    return NextResponse.json({ error: `Webhook error: ${msg}` }, { status: 400 })
  }

  if (event.type === 'checkout.session.completed') {
    const session = event.data.object

    const order = await prisma.order.findUnique({
      where: { stripeSessionId: session.id },
    })

    if (!order) {
      console.error('[webhook] Order not found for session:', session.id)
      return NextResponse.json({ received: true })
    }

    if (order.status !== 'PENDING') {
      // Already processed (idempotent)
      return NextResponse.json({ received: true })
    }

    const updated = await prisma.order.update({
      where: { id: order.id },
      data: {
        status: 'PAID',
        stripePaymentId: session.payment_intent as string ?? null,
      },
    })

    // Send emails + sync to Google Sheets (non-blocking)
    await Promise.allSettled([
      sendOrderConfirmationToClient(updated),
      sendNewOrderNotificationToAdmin(updated),
      appendOrderToSheet(updated),
    ])
  }

  return NextResponse.json({ received: true })
}
