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

export const GET = safeHandler(async (req: Request) => {
  await requireAuth()
  const { searchParams } = new URL(req.url)

  const status = searchParams.get('status')
  const assignedToId = searchParams.get('assignedToId')
  const priority = searchParams.get('priority')
  const bookingId = searchParams.get('bookingId')
  const queryId = searchParams.get('queryId')

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

  const tasks = await prisma.task.findMany({
    where,
    include: {
      assignedTo: { select: { name: true } },
      createdBy: { select: { name: true } },
      booking: { select: { bookingNo: true } },
      query: { select: { queryNo: true } },
    },
    orderBy: [
      { dueDate: { sort: 'asc', nulls: 'last' } },
      { createdAt: 'desc' },
    ],
  })

  return NextResponse.json(tasks)
})

export const POST = safeHandler(async (req: Request) => {
  const session = await requireAuth()
  const data = await req.json()
  const createdById = session.user.id

  const task = await prisma.task.create({
    data: {
      title: data.title,
      description: data.description,
      assignedToId: data.assignedToId,
      createdById,
      bookingId: data.bookingId || null,
      queryId: data.queryId || null,
      dueDate: data.dueDate ? new Date(data.dueDate) : null,
      priority: data.priority || 'MEDIUM',
      status: data.status || 'TODO',
    },
    include: {
      assignedTo: { select: { name: true } },
      createdBy: { select: { name: true } },
      booking: { select: { bookingNo: true } },
      query: { select: { queryNo: true } },
    },
  })

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

  return NextResponse.json(task)
})
