import { getSession } from '@/lib/session'
import { createPost, topicIsReplyable } 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 topicId = Number(b.topicId)
  const text = String(b.text ?? '').trim()
  if (!topicId || !text) return Response.json({ success: false, error: 'emptyError' })
  if (!(await topicIsReplyable(topicId))) return Response.json({ success: false, error: 'topicLocked' })
  await createPost(topicId, session.username, session.accountId, text)
  return Response.json({ success: true })
}
