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

let { User, Post, Report, 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('/post', auth, async(req, res, next) => {
	try {
		let post = await Post.findByPk(req.body.postId)

		if(!post) throw Report.InvalidPostId(req.body.postId)

		let user = await User.findOne({
			where: { username: req.userData.username }
		})

		let report = await Report.create({ reason: req.body.reason })
		report.setFlaggedByUser(user)
		report.setPost(post)

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

router.post('/user', auth, async(req, res, next) => {
	try {
		let reportedUser = await Post.findByPk(req.body.userId)

		if(!reportedUser) throw Report.InvalidUserId(req.body.userId)

		let user = await User.findOne({
			where: { username: req.userData.username }
		})

		let report = await Report.create({ reason: req.body.reason })
		report.setFlaggedByUser(user)
		report.setReportedUser(reportedUser)

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

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.get('/', auth, async(req, res, next) => {
	try {
		let reports = await Report.findAll({
			include: [
				{ model: User, as: 'FlaggedByUser', attributes: { exclude: ['hash', 'email', 'emailVerified', 'koins', 'currency2', 'emailToken', 'passwordResetExpiry', 'passwordResetToken', 'experimentMode', 'developerMode', 'cookieOptOut', 'deleteCode', 'jwtOffset'] } },
				{ model: Post, include: Post.includeOptions(), attributes: { exclude: ['hash', 'email', 'emailVerified', 'koins', 'currency2', 'emailToken', 'passwordResetExpiry', 'passwordResetToken', 'experimentMode', 'developerMode', 'cookieOptOut', 'deleteCode', 'jwtOffset'] } }
			]
		})

		res.json(reports)
	} catch (e) { next(e) }
})
router.delete('/:id', auth, async(req, res, next) => {
	try {
		let report = await Report.findByPk(req.params.id)
		if(!report) throw Report.InvalidPostId(req.params.id)

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

module.exports = router
