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

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

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

const router = Router()

router.get('/list', async (req, res) => {
  const items = await ListModel
    .find({})
    .populate('items')
    .exec()

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

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

  const list = await ListModel
    .findById(todoId)
    .populate('items')
    .exec()

  if (!list) {
    throw new Error('list not found')
  }

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

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

router.post('/', requiredValidate('title'), async (req, res) => {
  const { title } = req.body
  const userId = req.auth.id

  const list = await ListModel.create({ title, createdBy: userId })

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

router.post('/item', requiredValidate('todoId', 'title'), async (req, res) => {
  const { todoId, title } = req.body

  const list = await ListModel.findById(todoId)

  if (!list) {
    throw new Error('list not found')
  }

  const userId = req.auth.id
  const item = await ItemModel.create({ title, createdBy: userId })

  list.items.push(item)
  await list.save()

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

// closed = new Date().toISOString()
router.patch('/item/:itemId', async (req, res) => {
  const { itemId } = req.params
  const { title, done } = req.body

  const item = await ItemModel.findById(itemId)

  if (!item) {
    throw new Error('item not found')
  }

  if (title) {
    item.title = title
  }

  if (done) {
    item.done = done
    item.closed = done ? new Date().toISOString() : null
  }

  await item.save()

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

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

  await ItemModel.findByIdAndDelete(itemId)

  res.send(getAnswer(null, { ok: true }))
})


module.exports = router
