import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { id } = await params
  const body = await req.json()

  const prazo = await prisma.prazo.findFirst({
    where: { id, userId: session.user.id },
  })

  if (!prazo) {
    return NextResponse.json({ error: 'Prazo não encontrado' }, { status: 404 })
  }

  const updated = await prisma.prazo.update({
    where: { id },
    data: {
      ...(body.title !== undefined && { title: body.title }),
      ...(body.description !== undefined && { description: body.description }),
      ...(body.processNumber !== undefined && { processNumber: body.processNumber }),
      ...(body.court !== undefined && { court: body.court }),
      ...(body.deadline !== undefined && { deadline: new Date(body.deadline) }),
      ...(body.alertDays !== undefined && { alertDays: body.alertDays }),
      ...(body.status !== undefined && { status: body.status }),
      ...(body.priority !== undefined && { priority: body.priority }),
    },
  })

  return NextResponse.json({ prazo: updated })
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
  }

  const { id } = await params

  const prazo = await prisma.prazo.findFirst({
    where: { id, userId: session.user.id },
  })

  if (!prazo) {
    return NextResponse.json({ error: 'Prazo não encontrado' }, { status: 404 })
  }

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

  return NextResponse.json({ success: true })
}
