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

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

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

router.post('/', auth, async(req, res, next) => {
	try {
		let user = await User.findOne({ where: { username: req.body.username } })
		if(!user) throw Errors.sequelizeValidation(Sequelize, {
			error: 'user does not exist',
			value: req.body.userId
		})

		AuditLog.create({UserId: req.userData.UserId, action: req.userData.username + ' banned ' + req.body.username + ' and succeeded (banned).'})

		let ban = await Ban.create({
			message: req.body.message,
			ipBanned: req.body.ipBanned,
			ReadOnlyMode: req.body.ReadOnlyMode,
			DisableLogin: req.body.DisableLogin,
		})
		await ban.setUser(user)

		let ret = await ban.reload({
			include: [{
				model: User,
				attributes: ['username', 'description', 'color', 'createdAt']
			}]
		})

		res.json(ret.toJSON())
	} catch (e) { next(e) }
})

router.get('/', auth, async(req, res, next) => {
	try {
		let bans = await Ban.findAll({
			include: [User]
		})

		res.json(bans.map(b => b.toJSON()))
	} catch (e) { next(e) }
})

router.delete('/:ban_id', auth, async(req, res, next) => {
	try {
		let ban = await Ban.findByPk(req.params.ban_id)
		if(!ban) throw Errors.sequelizeValidation(Sequelize, {
			error: 'ban does not exist',
			value: req.body.userId
		})
		AuditLog.create({UserId: req.userData.UserId, action: req.userData.username + ' unbanned UID: ' + ban.UserId + ' and succeeded (unbanned).'})

		await ban.destroy()
		res.json({ success: true })

	} catch (e) { next(e) }
})

module.exports = router
