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

const Errors = require('../lib/errors')
let { User, Team, teamWall, Notification, Ban, Sequelize, sequelize } = require('../models')
let pagination = require('../lib/pagination.js')
const rateLimit = require("express-rate-limit");
const postLimiter = rateLimit({
    windowMs: 60000,
    max: 10,
    message: "{\"errors\":[{\"name\":\"rateLimit\",\"message\":\"You may only make 10 requests to this endpoint per minute.\",\"status\":429}]}"
});
router.get('/show/:username', async(req, res, next) => {
    try {
        let { limit } = pagination.getPaginationProps(req.query, true)

        let postInclude = {
            model: userWall,
            limit,
            order: [['id', 'DESC']]
        }

        let user = await teamWall.findOne(postInclude)
        if (!user) throw Errors.accountDoesNotExist

        let meta = await user.getMeta(limit)
        let Posts = await teamWall.find(postInclude)

        res.json(Object.assign( user.toJSON(limit), { meta, Posts } ))    } catch (e) { next(e) }
})

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

router.post('/post', postLimiter, auth, async(req, res, next) => {
    let queryObj = {
        attributes: {include: ['emailVerified']},
        where: {username: req.userData.username}
    }
    let getSessionId = {
        attributes: {include: ['id']},
        where: {username: req.userData.username}
    }
    let teamToId = {
        attributes: {include: ['id']},
        where: {username: req.body.username}
    }
    let user = await User.findOne(queryObj)
    let sessionId = await User.findOne(getSessionId)
    let getWallUser = await Team.findOne(teamToId)
    try {
        //Will throw an error if banned
        await Ban.ReadOnlyMode(req.userData.UserId)

        if(getWallUser.banned) {
            throw Errors.teamBanned
        }

        if (req.body.mentions) {
            uniqueMentions = Notification.filterMentions(req.body.mentions)
        }

        if (!user.emailVerified) {
            throw Errors.verifyEmail
        }

        if(getWallUser.userWallOptOut) {
            throw Errors.userWallOptOut
        }

        if(teamToId.id == "null") throw Errors.sequelizeValidation(Sequelize, {
            error: 'User doesn\'t exist',
            path: 'id'
        })

        user = await teamWall.findOne({ where: {
                fromUserId: sessionId.id
            }})

        post = await teamWall.create({content: req.body.content, postNumber: "0", teamId: getWallUser.id, fromUserId: req.userData.UserId})

        if (uniqueMentions.length) {
            let ioUsers = req.app.get('io-users')
            let io = req.app.get('io')

            for (const mention of uniqueMentions) {
                let mentionNotification = await Notification.createPostNotification({
                    usernameTo: mention,
                    userFrom: user,
                    type: 'mention',
                    post
                })

                if (mentionNotification) {
                    await mentionNotification.emitNotificationMessage(ioUsers, io)
                }
            }
        }

        res.json({success: true})

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

router.delete('/:post_id', auth, async(req, res, next) => {
    try {
        if(!req.userData.admin){
            res.status(401)
            res.json({errors: [Errors.requestNotAuthorized]})
        }
        let post = await userWall.findByPk(req.params.post_id)
        if(!post) throw Errors.sequelizeValidation(Sequelize, {
            error: 'post does not exist',
            path: 'id'
        })

        await post.update({ content: '[This post has been removed by an administrator]', removed: true })

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

module.exports = router
