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

export const GET = safeHandler(async (req: Request) => {
  const session = await requireAuth()

  const { searchParams } = new URL(req.url)
  const status = searchParams.get('status')
  const queryId = searchParams.get('queryId')
  const bookingId = searchParams.get('bookingId')
  const paymentId = searchParams.get('paymentId')

  const where: Record<string, unknown> = {}
  if (status) where.status = status
  if (queryId) where.queryId = queryId
  if (bookingId) where.bookingId = bookingId
  if (paymentId) where.paymentId = paymentId

  const reminders = await prisma.reminder.findMany({
    where,
    include: {
      query: { select: { queryNo: true } },
      booking: { select: { bookingNo: true } },
      payment: { select: { paymentNo: true } },
      createdBy: { select: { name: true } },
    },
    orderBy: { reminderDate: 'asc' },
  })

  return NextResponse.json(reminders)
})

export const POST = safeHandler(async (req: Request) => {
  const session = await requireAuth()

  const body = await req.json()
  const { queryId, bookingId, paymentId, reminderDate, message } = body

  const reminder = await prisma.reminder.create({
    data: {
      queryId: queryId || null,
      bookingId: bookingId || null,
      paymentId: paymentId || null,
      reminderDate: new Date(reminderDate),
      message,
      createdById: session.user.id,
    },
    include: {
      query: { select: { queryNo: true } },
      booking: { select: { bookingNo: true } },
      payment: { select: { paymentNo: true } },
      createdBy: { select: { name: true } },
    },
  })

  return NextResponse.json(reminder)
})
