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

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

  const [nodes, businessLines] = await Promise.all([
    prisma.processNode.findMany({
      orderBy: [{ businessLineId: 'asc' }, { order: 'asc' }, { name: 'asc' }],
      include: {
        businessLine: { select: { id: true, name: true, slug: true } },
        _count: { select: { documents: true, children: true } },
      },
    }),
    prisma.businessLine.findMany({ orderBy: { name: 'asc' } }),
  ])

  return NextResponse.json({ nodes, businessLines })
}

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 { name, description, type, parentId, businessLineId, order } = body

  if (!name || !type) return NextResponse.json({ error: 'Nombre y tipo requeridos' }, { status: 400 })

  const node = await prisma.processNode.create({
    data: {
      name,
      description: description || null,
      type: type as ProcessType,
      parentId: parentId ? parseInt(String(parentId)) : null,
      businessLineId: businessLineId ? parseInt(String(businessLineId)) : null,
      order: parseInt(String(order ?? 0)) || 0,
    },
    include: { businessLine: { select: { id: true, name: true, slug: true } } },
  })

  await prisma.auditLog.create({
    data: { userId: u.userId, action: 'CREATE_PROCESS', entity: 'ProcessNode', entityId: node.id, details: name },
  })

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