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

export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

  const id = parseInt(params.id)
  const body = await req.json()
  const { name, description, businessLineId, order } = body

  const node = await prisma.processNode.update({
    where: { id },
    data: {
      name,
      description: description || null,
      businessLineId: businessLineId ? parseInt(String(businessLineId)) : null,
      order: parseInt(String(order ?? 0)) || 0,
    },
  })

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

  return NextResponse.json(node)
}

async function deleteRecursive(id: number) {
  const children = await prisma.processNode.findMany({ where: { parentId: id }, select: { id: true } })
  for (const child of children) await deleteRecursive(child.id)
  await prisma.document.deleteMany({ where: { processNodeId: id } })
  await prisma.processNode.delete({ where: { id } })
}

export async function DELETE(_req: NextRequest, { params }: { params: { id: string } }) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

  const id = parseInt(params.id)
  const node = await prisma.processNode.findUnique({ where: { id } })
  if (!node) return NextResponse.json({ error: 'No encontrado' }, { status: 404 })

  await deleteRecursive(id)

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

  return NextResponse.json({ ok: true })
}
