import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { createQrSourceSchema } from "@/lib/validators"
import { customAlphabet } from "nanoid"

const generateCode = customAlphabet("23456789abcdefghjkmnpqrstuvwxyz", 8)

interface QrPledge {
  amountPence: number
  status: string
}

interface QrRow {
  id: string
  label: string
  code: string
  volunteerName: string | null
  tableName: string | null
  scanCount: number
  createdAt: Date
  _count: { pledges: number }
  pledges: QrPledge[]
}

// GET QR sources for event
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    if (!prisma) {
      return NextResponse.json([])
    }
    const sources = await prisma.qrSource.findMany({
      where: { eventId: id },
      include: {
        _count: { select: { pledges: true } },
        pledges: { select: { amountPence: true, status: true } },
      },
      orderBy: { createdAt: "desc" },
    }) as QrRow[]

    return NextResponse.json(
      sources.map((s: QrRow) => ({
        id: s.id,
        label: s.label,
        code: s.code,
        volunteerName: s.volunteerName,
        tableName: s.tableName,
        scanCount: s.scanCount,
        pledgeCount: s._count.pledges,
        totalPledged: s.pledges.reduce((sum: number, p: QrPledge) => sum + p.amountPence, 0),
        createdAt: s.createdAt,
      }))
    )
  } catch (error) {
    console.error("QR sources GET error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}

// POST create QR source
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    if (!prisma) {
      return NextResponse.json({ error: "Database not configured" }, { status: 503 })
    }
    const body = await request.json()

    const parsed = createQrSourceSchema.safeParse(body)
    if (!parsed.success) {
      return NextResponse.json({ error: "Invalid data", details: parsed.error.flatten() }, { status: 400 })
    }

    const event = await prisma.event.findUnique({
      where: { id },
      select: { id: true },
    })

    if (!event) {
      return NextResponse.json({ error: "Event not found" }, { status: 404 })
    }

    const code = generateCode()

    const qrSource = await prisma.qrSource.create({
      data: {
        ...parsed.data,
        code,
        eventId: id,
      },
    })

    return NextResponse.json(qrSource, { status: 201 })
  } catch (error) {
    console.error("QR source creation error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
