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, mobile, active, order } = body

  const entry = await prisma.directoryEntry.update({
    where: { id },
    data: {
      name,
      position: position || null,
      area: area || null,
      email: email || null,
      phone: phone || null,
      mobile: mobile || null,
      active: active ?? true,
      order: order ?? 0,
    },
  })

  return NextResponse.json(entry)
}

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.directoryEntry.delete({ where: { id } })

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