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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    if (!prisma) {
      return NextResponse.json({ error: "Database not configured" }, { status: 503 })
    }
    const { id } = await params
    const pledge = await prisma.pledge.findUnique({
      where: { id },
      include: { event: { select: { name: true } } },
    })
    if (!pledge) {
      return NextResponse.json({ error: "Not found" }, { status: 404 })
    }
    return NextResponse.json({
      id: pledge.id,
      reference: pledge.reference,
      amountPence: pledge.amountPence,
      rail: pledge.rail,
      status: pledge.status,
      donorName: pledge.donorName,
      donorEmail: pledge.donorEmail,
      eventName: pledge.event.name,
    })
  } catch (error) {
    console.error("Pledge GET error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}

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

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

    const existing = await prisma.pledge.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json({ error: "Pledge not found" }, { status: 404 })
    }

    const updateData: Record<string, unknown> = {
      status: parsed.data.status,
      notes: parsed.data.notes,
    }

    if (parsed.data.status === "paid") {
      updateData.paidAt = new Date()
    }
    if (parsed.data.status === "cancelled") {
      updateData.cancelledAt = new Date()
    }

    const pledge = await prisma.pledge.update({
      where: { id },
      data: updateData,
    })

    // If paid or cancelled, skip remaining reminders
    if (["paid", "cancelled"].includes(parsed.data.status)) {
      await prisma.reminder.updateMany({
        where: { pledgeId: id, status: "pending" },
        data: { status: "skipped" },
      })
    }

    return NextResponse.json(pledge)
  } catch (error) {
    console.error("Pledge update error:", error)
    return NextResponse.json({ error: "Internal error" }, { status: 500 })
  }
}
