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, position, area, email, phone, parentId, order } = body

  const node = await prisma.orgNode.update({
    where: { id },
    data: {
      name,
      position: position || null,
      area: area || null,
      email: email || null,
      phone: phone || null,
      parentId: parentId ? parseInt(parentId) : null,
      order: order ?? 0,
    },
  })

  return NextResponse.json(node)
}

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)

  await prisma.orgNode.updateMany({ where: { parentId: id }, data: { parentId: null } })
  await prisma.orgNode.delete({ where: { id } })

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