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

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

  const { searchParams } = new URL(req.url)
  const status = searchParams.get('status')
  const priority = searchParams.get('priority')

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const where: any = { userId: session.user.id }
  if (status) where.status = status
  if (priority) where.priority = priority

  const prazos = await prisma.prazo.findMany({
    where,
    orderBy: { deadline: 'asc' },
  })

  return NextResponse.json({ prazos })
}

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

  const body = await req.json()
  const { title, description, processNumber, court, deadline, alertDays, priority } = body

  // Input validation
  if (typeof title !== "string" || title.length > 500) {
    return NextResponse.json({ error: "Título inválido (máx 500 caracteres)" }, { status: 400 })
  }
  if (description && typeof description === "string" && description.length > 5000) {
    return NextResponse.json({ error: "Descrição muito longa (máx 5000 caracteres)" }, { status: 400 })
  }
  if (!title || !deadline) {
    return NextResponse.json({ error: 'Título e prazo são obrigatórios' }, { status: 400 })
  }

  const prazo = await prisma.prazo.create({
    data: {
      userId: session.user.id,
      title,
      description: description || null,
      processNumber: processNumber || null,
      court: court || null,
      deadline: new Date(deadline),
      alertDays: alertDays || 3,
      priority: priority || 'MEDIA',
      status: 'PENDENTE',
    },
  })

  return NextResponse.json({ prazo }, { status: 201 })
}
