import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { constructWebhookEvent } from "@/lib/stripe"

export async function POST(request: NextRequest) {
  try {
    const body = await request.text()
    const signature = request.headers.get("stripe-signature") || ""

    const event = constructWebhookEvent(body, signature)
    if (!event) {
      return NextResponse.json({ error: "Invalid signature" }, { status: 400 })
    }

    switch (event.type) {
      case "checkout.session.completed": {
        const session = event.data.object as { id: string; metadata: Record<string, string>; payment_status: string }
        const pledgeId = session.metadata?.pledge_id

        if (pledgeId && session.payment_status === "paid") {
          await prisma.pledge.update({
            where: { id: pledgeId },
            data: {
              status: "paid",
              paidAt: new Date(),
            },
          })

          // Update payment record
          await prisma.payment.updateMany({
            where: {
              pledgeId,
              providerRef: session.id,
            },
            data: {
              status: "confirmed",
              receivedAt: new Date(),
            },
          })

          // Track analytics
          await prisma.analyticsEvent.create({
            data: {
              eventType: "payment_matched",
              pledgeId,
              metadata: { provider: "stripe", sessionId: session.id },
            },
          })
        }
        break
      }

      case "payment_intent.succeeded": {
        const pi = event.data.object as { id: string; metadata: Record<string, string> }
        const pledgeId = pi.metadata?.pledge_id

        if (pledgeId) {
          await prisma.pledge.update({
            where: { id: pledgeId },
            data: {
              status: "paid",
              paidAt: new Date(),
            },
          })
        }
        break
      }

      case "payment_intent.payment_failed": {
        const pi = event.data.object as { id: string; metadata: Record<string, string> }
        const pledgeId = pi.metadata?.pledge_id

        if (pledgeId) {
          await prisma.pledge.update({
            where: { id: pledgeId },
            data: { status: "overdue" },
          })
        }
        break
      }
    }

    return NextResponse.json({ received: true })
  } catch (error) {
    console.error("Stripe webhook error:", error)
    return NextResponse.json({ error: "Webhook handler failed" }, { status: 500 })
  }
}
