const { Router } = require('express')
const { expressjwt } = require('express-jwt')

const { getAnswer } = require('../../utils/common')

const { CommentModel } = require('./model/todo/comment')
const { ListModel } = require('./model/todo/list')
const { ItemModel } = require('./model/todo/item')
const { TOKEN_KEY } = require('./const')

const router = Router()

router.get('/:todoId/:itemId', async (req, res) => {
  const { todoId, itemId } = req.params

  const todo = await ListModel.findById(todoId)
  if (!todo) {
    return res.send(getAnswer(new Error('no such todo')))
  }

  const item = await ItemModel.findById(itemId).populate({ path: 'comments', populate: { path: 'author' } }).exec()
  if (!item) {
    return res.send(getAnswer(new Error('no such item')))
  }

  res.send(getAnswer(null, item))
})

router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }))

router.post('/:todoId/:itemId', async (req, res) => {
  const { text } = req.body
  const { todoId, itemId } = req.params

  const todo = await ListModel.findById(todoId)

  if (!todo) {
    return res.send(getAnswer(new Error('no such todo')))
  }

  const item = await ItemModel.findById(itemId)
  if (!item) {
    return res.send(getAnswer(new Error('no such item')))
  }
  const userId = req.auth.id

  const comment = await CommentModel.create({ text, author: userId, createdBy: userId })
  await item.addComment(comment.id)

  res.send(getAnswer(null, comment))
})

module.exports = router
