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

export async function GET(request: NextRequest) {
  try {
    const pledgeId = request.nextUrl.searchParams.get("pledge_id")
    const redirectFlowId = request.nextUrl.searchParams.get("redirect_flow_id")

    if (!pledgeId) {
      return NextResponse.redirect(new URL("/", request.url))
    }

    const pledge = await prisma.pledge.findUnique({
      where: { id: pledgeId },
      include: { event: true, paymentInstruction: true },
    })

    if (!pledge) {
      return NextResponse.redirect(new URL("/", request.url))
    }

    // If we have a redirect flow ID, complete the GoCardless flow
    if (redirectFlowId) {
      const result = await completeRedirectFlow(redirectFlowId, pledgeId)

      if (result) {
        // Save mandate ID
        if (pledge.paymentInstruction) {
          await prisma.paymentInstruction.update({
            where: { id: pledge.paymentInstruction.id },
            data: { gcMandateId: result.mandateId },
          })
        }

        // Create the payment against the mandate
        const payment = await createPayment({
          amountPence: pledge.amountPence,
          mandateId: result.mandateId,
          reference: pledge.reference,
          pledgeId: pledge.id,
          description: `${pledge.event.name} — ${pledge.reference}`,
        })

        if (payment) {
          // Update pledge status
          await prisma.pledge.update({
            where: { id: pledgeId },
            data: { status: "initiated" },
          })

          // Record payment
          await prisma.payment.create({
            data: {
              pledgeId: pledge.id,
              provider: "gocardless",
              providerRef: payment.paymentId,
              amountPence: pledge.amountPence,
              status: "pending",
              matchedBy: "auto",
            },
          })
        }
      }
    }

    // Redirect to success page
    const successUrl = `/p/success?pledge_id=${pledgeId}&rail=gocardless`
    return NextResponse.redirect(new URL(successUrl, request.url))
  } catch (error) {
    console.error("GoCardless callback error:", error)
    return NextResponse.redirect(new URL("/", request.url))
  }
}
