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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { eventType, pledgeId, eventId, qrSourceId, metadata } = body

    // Fire and forget - don't block on errors
    if (pledgeId?.startsWith("demo-")) {
      return NextResponse.json({ ok: true })
    }

    if (!prisma) {
      return NextResponse.json({ ok: true })
    }

    await prisma.analyticsEvent.create({
      data: {
        eventType: eventType || "unknown",
        pledgeId: pledgeId || null,
        eventId: eventId || null,
        qrSourceId: qrSourceId || null,
        metadata: metadata || {},
      },
    })

    return NextResponse.json({ ok: true })
  } catch {
    // Never fail analytics
    return NextResponse.json({ ok: true })
  }
}
