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

export async function GET(request: NextRequest) {
  try {
    const eventId = request.nextUrl.searchParams.get("eventId")
    if (!eventId || !prisma) {
      // Return smart defaults
      return NextResponse.json(await suggestAmounts({ eventName: "Charity Event" }))
    }

    // Get real peer data from the event
    const pledges = await prisma.pledge.findMany({
      where: { eventId, status: { not: "cancelled" } },
      select: { amountPence: true },
      orderBy: { amountPence: "asc" },
    })

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

    if (pledges.length === 0) {
      return NextResponse.json(await suggestAmounts({
        eventName: event?.name || "Charity Event",
      }))
    }

    const amounts = pledges.map(p => p.amountPence)
    const avg = Math.round(amounts.reduce((a, b) => a + b, 0) / amounts.length)
    const median = amounts[Math.floor(amounts.length / 2)]
    const top = amounts[amounts.length - 1]

    return NextResponse.json(await suggestAmounts({
      eventName: event?.name || "Charity Event",
      avgPledge: avg,
      medianPledge: median,
      pledgeCount: pledges.length,
      topAmount: top,
    }))
  } catch (error) {
    console.error("AI suggest error:", error)
    return NextResponse.json(await suggestAmounts({ eventName: "Charity Event" }))
  }
}
