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 search = searchParams.get('search') || ''
  const tribunal = searchParams.get('tribunal') || ''
  const area = searchParams.get('area') || ''
  const relator = searchParams.get('relator') || ''
  const dateFrom = searchParams.get('dateFrom') || ''
  const dateTo = searchParams.get('dateTo') || ''
  const page = Math.max(1, Math.min(1000, parseInt(searchParams.get('page') || '1', 10) || 1))
  const perPage = Math.max(1, Math.min(50, parseInt(searchParams.get('perPage') || '10', 10) || 10))

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const where: any = {}

  if (search) {
    where.OR = [
      { ementa: { contains: search, mode: 'insensitive' } },
      { numero: { contains: search, mode: 'insensitive' } },
      { relator: { contains: search, mode: 'insensitive' } },
    ]
  }

  if (tribunal) {
    where.tribunal = tribunal
  }

  if (area) {
    where.area = area
  }

  if (relator) {
    where.relator = { contains: relator, mode: 'insensitive' }
  }

  if (dateFrom || dateTo) {
    // data is stored as string "YYYY-MM-DD"
    if (dateFrom) {
      where.data = { ...(where.data || {}), gte: dateFrom }
    }
    if (dateTo) {
      where.data = { ...(where.data || {}), lte: dateTo }
    }
  }

  const [total, results] = await Promise.all([
    prisma.jurisprudencia.count({ where }),
    prisma.jurisprudencia.findMany({
      where,
      orderBy: { data: 'desc' },
      skip: (page - 1) * perPage,
      take: perPage,
    }),
  ])

  return NextResponse.json({
    results,
    total,
    page,
    perPage,
    totalPages: Math.ceil(total / perPage),
  })
}
