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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; qrId: string }> }
) {
  try {
    const { qrId } = await params
    const baseUrl = process.env.BASE_URL || "http://localhost:3000"

    // qrId is actually used to look up the code, but for simplicity use the code from query
    const code = request.nextUrl.searchParams.get("code") || qrId
    
    const buffer = await generateQrBuffer({
      baseUrl,
      code,
      width: 800,
      margin: 2,
    })

    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": "image/png",
        "Content-Disposition": `attachment; filename="qr-${code}.png"`,
      },
    })
  } catch (error) {
    console.error("QR download error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
