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

// GoCardless sends webhook events for payment status changes
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const events = body.events || []

    for (const event of events) {
      const { resource_type, action, links } = event

      if (resource_type === "payments") {
        const paymentId = links?.payment

        if (!paymentId) continue

        // Find our payment record
        const payment = await prisma.payment.findFirst({
          where: { providerRef: paymentId, provider: "gocardless" },
          include: { pledge: true },
        })

        if (!payment) continue

        switch (action) {
          case "confirmed":
          case "paid_out":
            await prisma.pledge.update({
              where: { id: payment.pledgeId },
              data: { status: "paid", paidAt: new Date() },
            })
            await prisma.payment.update({
              where: { id: payment.id },
              data: { status: "confirmed", receivedAt: new Date() },
            })
            await prisma.analyticsEvent.create({
              data: {
                eventType: "payment_matched",
                pledgeId: payment.pledgeId,
                metadata: { provider: "gocardless", action, paymentId },
              },
            })
            break

          case "failed":
          case "cancelled":
            await prisma.pledge.update({
              where: { id: payment.pledgeId },
              data: { status: action === "cancelled" ? "cancelled" : "overdue" },
            })
            await prisma.payment.update({
              where: { id: payment.id },
              data: { status: "failed" },
            })
            break
        }
      }

      if (resource_type === "mandates" && action === "cancelled") {
        // Mandate cancelled by bank/customer
        const mandateId = links?.mandate
        if (mandateId) {
          const instruction = await prisma.paymentInstruction.findFirst({
            where: { gcMandateId: mandateId },
          })
          if (instruction) {
            await prisma.pledge.update({
              where: { id: instruction.pledgeId },
              data: { status: "cancelled", cancelledAt: new Date() },
            })
          }
        }
      }
    }

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