const router = require('express').Router()
const { expressjwt } = require('express-jwt')
const ObjectId = require('mongodb').ObjectID

const { BASKET_JWT_TOKEN } = require('./key')

const { getShoppingList, deleteItem, boughtItem, incCountItem, getResponse, addListItem } = require('./controller')

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

router.get('/:id', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    // eslint-disable-next-line no-return-assign
    const { id } = req.params
    // eslint-disable-next-line no-return-assign
    const listData = await getShoppingList({ userId, id }).catch((e) => error = e.message)
    res.send(getResponse(error, listData))
})

router.post('/item/:id', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    // eslint-disable-next-line no-return-assign
    const { id } = req.params
    const { categoryId, text } = req.body
    const shoppingListData = await addListItem({
        userId, listId: id, categoryId, text,
    // eslint-disable-next-line no-return-assign
    }).catch((e) => error = e.message)
    res.send(getResponse(error, shoppingListData))
})

router.patch('/item/:id', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    // eslint-disable-next-line no-return-assign
    const { id } = req.params
    const { bought } = req.body.item
    // eslint-disable-next-line no-return-assign
    // eslint-disable-next-line max-len
    const itemData = await boughtItem({ userId, itemId: id, bought }).catch((e) => error = e.message)
    res.send(getResponse(error, itemData))
})

router.put('/item/:id', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    // eslint-disable-next-line no-return-assign
    const { id } = req.params
    const { count } = req.body
    // eslint-disable-next-line no-return-assign
    // eslint-disable-next-line max-len
    const itemData = await incCountItem({ userId, itemId: id, count }).catch((e) => error = e.message)
    res.send(getResponse(error, itemData))
})

router.delete('/item/:id', async (req, res) => {
    let error = null
    // eslint-disable-next-line no-return-assign
    const { id } = req.params
    // eslint-disable-next-line no-return-assign
    const itemData = await deleteItem({ itemId: id }).catch((e) => error = e.message)
    res.send(getResponse(error, itemData))
})

module.exports = router