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

type Params = { params: Promise<{ id: string }> }

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

  const task = await prisma.task.findUnique({
    where: { id },
    include: {
      assignedTo: { select: { name: true } },
      createdBy: { select: { name: true } },
      booking: { select: { bookingNo: true } },
      query: { select: { queryNo: true } },
    },
  })

  if (!task) throw new AuthError('Task not found', 404)

  return NextResponse.json(task)
})

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

  const existing = await prisma.task.findUnique({ where: { id } })
  if (!existing) throw new AuthError('Task not found', 404)

  const task = await prisma.task.update({
    where: { id },
    data: {
      title: data.title !== undefined ? data.title : undefined,
      description: data.description !== undefined ? data.description : undefined,
      assignedToId: data.assignedToId !== undefined ? data.assignedToId : undefined,
      bookingId: data.bookingId !== undefined ? data.bookingId : undefined,
      queryId: data.queryId !== undefined ? data.queryId : undefined,
      dueDate: data.dueDate !== undefined ? (data.dueDate ? new Date(data.dueDate) : null) : undefined,
      priority: data.priority !== undefined ? data.priority : undefined,
      status: data.status !== undefined ? data.status : undefined,
    },
    include: {
      assignedTo: { select: { name: true } },
      createdBy: { select: { name: true } },
      booking: { select: { bookingNo: true } },
      query: { select: { queryNo: true } },
    },
  })

  if (data.assignedToId && data.assignedToId !== existing.assignedToId) {
    await createNotification({
      userId: data.assignedToId,
      title: 'Task Assigned to You',
      message: `You have been assigned a task: ${task.title}`,
      type: 'INFO',
      module: 'TASK',
      link: `/dmcify/tasks`,
    })
  }

  return NextResponse.json(task)
})

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

  const task = await prisma.task.findUnique({ where: { id } })
  if (!task) throw new AuthError('Task not found', 404)

  await prisma.task.delete({ where: { id } })

  return NextResponse.json({ message: 'Deleted' })
})
