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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ token: string }> }
) {
  try {
    const { token } = await params

    if (!prisma) {
      return NextResponse.json({ error: "Database not configured" }, { status: 503 })
    }

    // Handle "demo" token — resolve to the first active event
    if (token === "demo") {
      const event = await prisma.event.findFirst({
        where: { status: "active" },
        include: { organization: { select: { name: true } } },
        orderBy: { createdAt: "asc" },
      })
      if (!event) {
        return NextResponse.json({ error: "No active events found" }, { status: 404 })
      }
      return NextResponse.json({
        id: event.id,
        name: event.name,
        organizationName: event.organization.name,
        qrSourceId: null,
        qrSourceLabel: null,
      })
    }

    const qrSource = await prisma.qrSource.findUnique({
      where: { code: token },
      include: {
        event: {
          include: {
            organization: { select: { name: true } },
          },
        },
      },
    })

    if (!qrSource || qrSource.event.status !== "active") {
      return NextResponse.json({ error: "This pledge link is no longer active" }, { status: 404 })
    }

    // Increment scan count
    await prisma.qrSource.update({
      where: { id: qrSource.id },
      data: { scanCount: { increment: 1 } },
    })

    return NextResponse.json({
      id: qrSource.event.id,
      name: qrSource.event.name,
      organizationName: qrSource.event.organization.name,
      qrSourceId: qrSource.id,
      qrSourceLabel: qrSource.label,
    })
  } catch (error) {
    console.error("QR resolve error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
