import { getSession } from '@/lib/session'
import { createTopic, forumIsPostable } from '@/lib/forum-write'

export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId || !session.username) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  let b: Record<string, string> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
  const forumId = Number(b.forumId)
  const name = String(b.name ?? '').trim()
  const text = String(b.text ?? '').trim()
  if (!forumId || !name || !text) return Response.json({ success: false, error: 'emptyError' })
  if (!(await forumIsPostable(forumId))) return Response.json({ success: false, error: 'invalidForum' })
  const topicId = await createTopic(forumId, name, session.username, session.accountId, text)
  return Response.json({ success: true, topicId })
}
