const express = require('express')
const { listTopics, getTopicDetail, findTopicByIdentifier, favoriteTopic, unfavoriteTopic } = require('../db')
const { requireAuth } = require('../middleware/auth')

const router = express.Router()

router.get('/', async (req, res) => {
  const topics = await listTopics(req.session?.userId || '', { includePrivate: !!req.session?.isAdmin })
  res.json({ topics })
})

router.post('/:topicId/favorite', requireAuth, async (req, res) => {
  const topic = await findTopicByIdentifier(req.params.topicId)
  if (!topic || topic.id === 'freeform') return res.status(404).json({ error: 'not_found' })
  await favoriteTopic({ userId: req.session.userId, topicId: topic.id })
  const topics = await listTopics(req.session.userId)
  const updated = topics.find((entry) => entry.id === topic.id) || { ...topic, isFavorited: true }
  res.json({ topic: updated })
})

router.delete('/:topicId/favorite', requireAuth, async (req, res) => {
  const topic = await findTopicByIdentifier(req.params.topicId)
  if (!topic || topic.id === 'freeform') return res.status(404).json({ error: 'not_found' })
  await unfavoriteTopic({ userId: req.session.userId, topicId: topic.id })
  const topics = await listTopics(req.session.userId)
  const updated = topics.find((entry) => entry.id === topic.id) || { ...topic, isFavorited: false }
  res.json({ topic: updated })
})

router.get('/:topicId', async (req, res) => {
  const detail = await getTopicDetail(req.params.topicId)
  if (!detail) return res.status(404).json({ error: 'not_found' })
  if (!detail.topic.isPublic && !req.session?.isAdmin) return res.status(404).json({ error: 'not_found' })
  res.json({ topic: detail.topic, items: detail.items })
})

module.exports = router
