/*Canopy - The next generation of stoner streaming software
Copyright (C) 2024-2025 Rainbownapkin and the TTN Community

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.*/

//npm imports
const {validationResult, matchedData} = require('express-validator');

//local imports
const {exceptionHandler, errorHandler} = require('../../../utils/loggerUtils');
const permissionModel = require('../../../schemas/permissionSchema');
const {userModel} = require('../../../schemas/user/userSchema');
const channelModel = require('../../../schemas/channel/channelSchema');

//api channel rank functions
module.exports.get = async function(req, res){
    try{
        //Get validation results
        const validResult = validationResult(req);

        //If we don't have any validation errors
        if(validResult.isEmpty()){
            //Get channel document from validated/sanatized chanName querystring
            const data = matchedData(req);
            const chanDB = await channelModel.findOne({name: data.chanName});

            //get userDB from session
            if(req.session.user != null){
                var userDB = await userModel.findOne({user: req.session.user.user});
            }

            //If for some reason there isn't any user found
            if(userDB == null){
                var userDB = {rank: "anon"};
            }

            //Setup empty array for our return data
            const userList = await chanDB.getRankList();

            //Send out the userlist we created
            res.status(200);
            res.send(Object.fromEntries(userList));
        }else{
            //If we received bad input, we have only one action: bitch, moan, and complain!
            res.status(400);
            res.send({errors: validResult.array()})
        }
    }catch(err){
        return exceptionHandler(res, err);
    }
}

module.exports.post = async function(req, res){
    try{
        //Get validation results
        const validResult = validationResult(req);

        //If we don't have any validation errors
        if(validResult.isEmpty()){
            const data = matchedData(req);
            //Get channel document from sanatized/validated data
            const chanDB = await channelModel.findOne({name: data.chanName});
            //Get user document from sanatized/validated data
            const userDB = await userModel.findOne({user: data.user});
            //Get requesting user rank from sanatized/validated data
            const chanRank = await chanDB.getChannelRank(req.session.user);
            //Get target user rank from sanatized/validated data
            const targetChanRank = await chanDB.getChannelRankByUserDoc(userDB);

            if(data.user == null || userDB == null){
                //If the user is null, scream and shout
                return errorHandler(res, 'User not found.', 'Bad Query');
            }else if(data.user == req.session.user.user){
                //If some smart-ass is trying self-privelege escalation
                return errorHandler(res, "No, you can't change your own rank, fuck off.", 'Unauthorized', 401);
            }else if(permissionModel.rankToNum(data.rank) >= permissionModel.rankToNum(chanRank)){
                //If the user is below the new rank of the user they're setting, scream and shout
                return errorHandler(res, "New rank must be below that of the user changing it.", 'Unauthorized', 401);
            }else if(permissionModel.rankToNum(targetChanRank) >= permissionModel.rankToNum(chanRank)){
                //If the user is below the original rank of the user they're setting, scream and shout
                return errorHandler(res, "You cannot promote/demote peer/outranking users.", 'Unauthorized', 401);
            }

            //Set rank
            await chanDB.setRank(userDB, data.rank);

            res.status(200);
            res.send(Object.fromEntries(await chanDB.getRankList()));
        }else{
            //If we received bad input, we have only one action: bitch, moan, and complain!
            res.status(400);
            res.send({errors: validResult.array()})
        }
    }catch(err){
        return exceptionHandler(res, err);
    }
}