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

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

router.all('*', auth, (req, res, next) => {
	if(req.userData.loggedIn) {
		next()
	} else {
		res.status(401)
		res.json({
			errors: [Errors.requestNotAuthorized]
		})
	}
})

router.get('/', auth, async(req, res, next) => {
	try {
		let Notifications = await Notification.findAll({
			where: {
				'UserId': req.userData.UserId
			},
			order: [['id', 'DESC']],
			include: [{
				model: PostNotification,
				include: [Post, { model: User, attributes: ['createdAt', 'username', 'color'] }]
			}]
		})

		let unreadCount = Notifications.reduce((acc, val) => {
			return val.read ? acc : acc+1
		}, 0)

		res.json({ Notifications, unreadCount })

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

router.put('/', auth, async(req, res, next) => {
	try {
		await Notification.update({ read: true }, {
			where: {
				'UserId': req.userData.UserId,
				'read': false
			}
		})

		res.json({ success: true })

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

router.put('/:id', auth, async(req, res, next) => {
	try {
		let updatedRows = await Notification.update({ interacted: true, read: true }, {
			where: {
				'UserId': req.userData.UserId,
				id: req.params.id
			}
		})

		if(updatedRows[0] === 0) {
			res.status(400)
			res.json({
				errors: [Errors.invalidParameter('id', 'invalid notification id')]
			})
		} else {
			res.json({ success: true })
		}
	} catch (e) { next(e) }
})

router.delete('/:id', auth, async(req, res, next) => {
	try {
		let deleted = await Notification.destroy({
			where: {
				'UserId': req.userData.UserId,
				id: req.params.id
			}
		})

		if(deleted) {
			res.json({ success: true })
		} else {
			res.status(400)
			res.json({
				errors: [Errors.invalidParameter('id', 'Notification already dismissed, or doesn\'t exist, maybe try not to spam it next time :)')]
			})
		}
	} catch (e) { next(e) }
})

module.exports = router
