import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { safeHandler, requireAuth, AuthError } from '@/lib/auth'

export const GET = safeHandler(async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
  await requireAuth()
  const { id } = await params

  const fund = await prisma.fundAllocation.findUnique({
    where: { id },
    include: {
      booking: { select: { bookingNo: true } },
      supplier: { select: { name: true } },
    },
  })
  if (!fund) throw new AuthError('Fund allocation not found', 404)

  return NextResponse.json(fund)
})

export const PUT = safeHandler(async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
  await requireAuth()
  const { id } = await params
  const data = await req.json()

  const fund = await prisma.fundAllocation.update({
    where: { id },
    data: {
      amount: data.amount !== undefined ? parseFloat(data.amount) : undefined,
      currency: data.currency || undefined,
      status: data.status || undefined,
      releasedDate: data.releasedDate !== undefined ? (data.releasedDate ? new Date(data.releasedDate) : null) : undefined,
      paidDate: data.paidDate !== undefined ? (data.paidDate ? new Date(data.paidDate) : null) : undefined,
      referenceNo: data.referenceNo !== undefined ? (data.referenceNo || null) : undefined,
      notes: data.notes !== undefined ? (data.notes || null) : undefined,
    },
  })

  return NextResponse.json(fund)
})

export const DELETE = safeHandler(async (_req: Request, { params }: { params: Promise<{ id: string }> }) => {
  await requireAuth()
  const { id } = await params

  const fund = await prisma.fundAllocation.findUnique({ where: { id } })
  if (!fund) throw new AuthError('Fund allocation not found', 404)
  if (fund.status !== 'BLOCKED') throw new AuthError('Only BLOCKED fund allocations can be deleted', 400)

  await prisma.fundAllocation.delete({ where: { id } })
  return NextResponse.json({ message: 'Deleted' })
})
