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 type = searchParams.get('type')
  const area = searchParams.get('area')
  const search = searchParams.get('search')
  const sort = searchParams.get('sort') || 'newest'
  const dateFrom = searchParams.get('dateFrom')
  const dateTo = searchParams.get('dateTo')

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

  if (type) where.type = type
  if (area) where.area = area
  if (search) where.title = { contains: search }

  if (dateFrom || dateTo) {
    where.createdAt = {}
    if (dateFrom) where.createdAt.gte = new Date(dateFrom)
    if (dateTo) where.createdAt.lte = new Date(dateTo + 'T23:59:59.999Z')
  }

  let orderBy: Record<string, string> = { createdAt: 'desc' }
  if (sort === 'oldest') orderBy = { createdAt: 'asc' }
  else if (sort === 'type') orderBy = { type: 'asc' }

  const documents = await prisma.document.findMany({
    where,
    orderBy,
    select: {
      id: true,
      title: true,
      type: true,
      area: true,
      status: true,
      wordCount: true,
      tokens: true,
      cost: true,
      createdAt: true,
    },
  })

  return NextResponse.json({ documents })
}
