import { getSession } from '@/lib/session'
import { getTopic, getForum } from '@/lib/forum'
import { setTopicFlag, moveTopic } from '@/lib/forum-write'
import { forumIsModerator } from '@/lib/forum-perm'

type Action = 'lock' | 'unlock' | 'sticky' | 'unsticky' | 'delete' | 'restore' | 'move'

/** Moderación de temas: bloquear, fijar, borrar. Solo moderadores. */
export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  if (!(await forumIsModerator(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })

  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 action = String(b.action ?? '') as Action
  if (!topicId) return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })

  const topic = await getTopic(topicId, true) // incluye borrados (ya verificado que es mod)
  if (!topic) return Response.json({ success: false, error: 'topicNotFound' }, { status: 404 })

  switch (action) {
    case 'lock':
      await setTopicFlag(topicId, 'locked', true)
      break
    case 'unlock':
      await setTopicFlag(topicId, 'locked', false)
      break
    case 'sticky':
      await setTopicFlag(topicId, 'sticky', true)
      break
    case 'unsticky':
      await setTopicFlag(topicId, 'sticky', false)
      break
    case 'delete':
      await setTopicFlag(topicId, 'deleted', true)
      return Response.json({ success: true, forumId: topic.forum_id })
    case 'restore':
      await setTopicFlag(topicId, 'deleted', false)
      break
    case 'move': {
      const newForumId = Number(b.forumId)
      if (!newForumId || newForumId === topic.forum_id) {
        return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
      }
      if (!(await getForum(newForumId))) {
        return Response.json({ success: false, error: 'invalidForum' }, { status: 400 })
      }
      await moveTopic(topicId, newForumId)
      return Response.json({ success: true })
    }
    default:
      return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  return Response.json({ success: true })
}
