import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { deleteCategory, updateCategory } from '@/lib/admin-forum'

export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  const ok = await deleteCategory(Number(id))
  return Response.json({ success: ok, error: ok ? undefined : 'categoryNotEmpty' })
}

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  let b: Record<string, unknown> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
  const name = String(b.name ?? '').trim()
  const nameEn = String(b.nameEn ?? '').trim() || null
  const order = Number(b.order) || 0
  if (!name) return Response.json({ success: false, error: 'emptyError' })
  await updateCategory(Number(id), name, nameEn, order)
  return Response.json({ success: true })
}
