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

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ token: string }> }
) {
  const { token } = await params
  const db = prisma

  const qrSource = await db.qrSource.findUnique({
    where: { code: token },
    include: {
      event: {
        include: { organization: { select: { name: true } } },
      },
      pledges: {
        orderBy: { createdAt: "desc" },
        select: {
          id: true,
          reference: true,
          amountPence: true,
          status: true,
          donorName: true,
          giftAid: true,
          createdAt: true,
        },
      },
    },
  })

  if (!qrSource) {
    return NextResponse.json({ error: "QR code not found" }, { status: 404 })
  }

  const pledges = qrSource.pledges
  const totalPledgedPence = pledges.reduce((s, p) => s + p.amountPence, 0)
  const totalPaidPence = pledges
    .filter((p) => p.status === "paid")
    .reduce((s, p) => s + p.amountPence, 0)

  return NextResponse.json({
    qrSource: {
      label: qrSource.label,
      volunteerName: qrSource.volunteerName,
      code: qrSource.code,
      scanCount: qrSource.scanCount,
    },
    event: {
      name: qrSource.event.name,
      organizationName: qrSource.event.organization.name,
    },
    pledges,
    stats: {
      totalPledges: pledges.length,
      totalPledgedPence,
      totalPaidPence,
      conversionRate: qrSource.scanCount > 0
        ? Math.round((pledges.length / qrSource.scanCount) * 100)
        : 0,
    },
  })
}
