import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser, unauthorized, forbidden } from '@/lib/sessionUser'
import { prisma } from '@/lib/prisma'
import { DocumentType, DocStatus, DocCategory } from '@prisma/client'

export async function GET(req: NextRequest) {
  const u = await getSessionUser()
  if (!u) return unauthorized()

  const { searchParams } = new URL(req.url)
  const type = searchParams.get('type') as DocumentType | null
  const status = searchParams.get('status') as DocStatus | null
  const category = searchParams.get('category') as DocCategory | null
  const businessLineId = searchParams.get('businessLineId') ? parseInt(searchParams.get('businessLineId')!) : undefined
  const processNodeId = searchParams.get('processNodeId') ? parseInt(searchParams.get('processNodeId')!) : undefined

  const docs = await prisma.document.findMany({
    where: {
      ...(type ? { type } : {}),
      ...(status ? { status } : {}),
      ...(category ? { category } : {}),
      ...(businessLineId ? { businessLineId } : {}),
      ...(processNodeId ? { processNodeId } : {}),
    },
    orderBy: { createdAt: 'desc' },
    include: {
      uploadedBy: { select: { name: true } },
      businessLine: { select: { name: true } },
      processNode: { select: { name: true } },
    },
  })

  const [businessLines, processNodes] = await Promise.all([
    prisma.businessLine.findMany({ orderBy: { name: 'asc' } }),
    prisma.processNode.findMany({ orderBy: { name: 'asc' }, select: { id: true, name: true, type: true } }),
  ])

  return NextResponse.json({ docs, businessLines, processNodes })
}

export async function POST(req: NextRequest) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

  const body = await req.json()
  const { title, description, type, category, version, status, fileUrl, filePath, processNodeId, businessLineId } = body

  if (!title || !type) return NextResponse.json({ error: 'Título y tipo requeridos' }, { status: 400 })

  const doc = await prisma.document.create({
    data: {
      title,
      description: description || null,
      type: type as DocumentType,
      category: (category ?? 'CORPORATIVO') as DocCategory,
      version: version ?? '1.0',
      status: (status ?? 'BORRADOR') as DocStatus,
      fileUrl: fileUrl || null,
      filePath: filePath || null,
      processNodeId: processNodeId ? parseInt(processNodeId) : null,
      businessLineId: businessLineId ? parseInt(businessLineId) : null,
      uploadedById: u.userId,
    },
  })

  await prisma.auditLog.create({
    data: { userId: u.userId, action: 'CREATE_DOCUMENT', entity: 'Document', entityId: doc.id, details: title },
  })

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