let express = require('express')
let router = express.Router()
const auth = require('../lib/auth')

let { User, Post, UnbanRequest, Sequelize } = require('../models')
const Errors = require('../lib/errors')

router.all('*', auth, (req, res, next) => {
    if(req.userData.loggedIn) {
        next()
    } else {
        res.status(401)
        res.json({
            errors: [Errors.requestNotAuthorized]
        })
    }
})
router.post('/', auth, async(req, res, next) => {
    try {
        let user = await User.findOne({
            where: { username: req.userData.username }
        })

        let unbanrequest = await UnbanRequest.create({ reason: req.body.reason })
        unbanrequest.UserId(user)

        res.json({
            success: true
        })
    } catch (e) { next(e) }
})

router.all('*', auth, (req, res, next) => {
    if(req.userData.admin) {
        next()
    } else {
        res.status(401)
        res.json({
            errors: [Errors.requestNotAuthorized]
        })
    }
})
router.get('/', auth, async(req, res, next) => {
    try {
        let unbanrequest = await UnbanRequest.findAll({
            include: [
                { model: User, as: 'UserId' },
                { model: Reason, include: Post.includeOptions() }
            ]
        })

        res.json(reports)
    } catch (e) { next(e) }
})
router.delete('/:id', auth, async(req, res, next) => {
    try {
        let unbanrequest = await UnbanRequest.findByPk(req.params.id)
        await report.destroy()
        res.json({ success: true })
    } catch (e) { next(e) }
})

module.exports = router
