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

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

const { getResponse, getCategory, postCategory } = require('./controller')

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

router.get('/', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    const categoryData = await getCategory({ userId }).catch((e) => error = e.message)
    res.send(getResponse(error, categoryData))
})

router.post('/', async (req, res) => {
    const userId = new ObjectId(req.auth.id)
    let error = null
    const categoryData = await postCategory({ userId, ...req.body }).catch((e) => error = e.message)
    res.send(getResponse(error, categoryData))
})

module.exports = router
