/*Canopy - The next generation of stoner streaming software
Copyright (C) 2024  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/>.*/

//local imports
const {userModel} = require('../schemas/userSchema');
const userBanModel = require('../schemas/userBanSchema')

//this module is good for keeping wrappers for userModel and other shit in that does more session handling than database access/modification.

module.exports.authenticateSession = async function(user, pass, req){

    //Authenticate the session
    const userDB = await userModel.authenticate(user, pass);
    const banDB = await userBanModel.checkBanByUserDoc(userDB);

    if(banDB){
        //Make the number a little prettier despite the lack of precision since we're not doing calculations here :P
        const expiration = banDB.getDaysUntilExpiration() < 1 ? 0 : banDB.getDaysUntilExpiration();
        if(banDB.permanent){
            throw new Error(`Your account has been permanently banned, and will be nuked from the database in: ${expiration} day(s)`);
        }else{
            throw new Error(`Your account has been temporarily banned, and will be reinstated in: ${expiration} day(s)`);
        }
    }

    //Tattoo the session with user and metadata
    //unfortunately store.all() does not return sessions w/ their ID so we had to improvise...
    //Not sure if this is just how connect-mongo is implemented or if it's an express issue, but connect-mongodb-session seems to not implement the all() function what so ever...
    req.session.seshid = req.session.id;
    req.session.authdate = new Date();
    req.session.authip = req.ip;
    req.session.user = {
        user: userDB.user,
        id: userDB.id,
        rank: userDB.rank
    }


    //userDB.activeSessions.push(sessionData);
    await userDB.save();

    //return user
    return userDB.user;
}

module.exports.killSession = async function(session){
    session.destroy();
}