
/*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/>.*/

//Config
const config = require('../../../../config.json');

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

//local imports
const {userModel} = require('../../../schemas/user/userSchema');
const emailChangeModel = require('../../../schemas/user/emailChangeSchema');
const mailUtils = require('../../../utils/mailUtils');
const {exceptionHandler, errorHandler} = require('../../../utils/loggerUtils');

//Gateway for generating request token and having it emailed to the user
module.exports.post = async function(req, res){
    try{
        //Check for validation errors
        const validResult = validationResult(req);

        //If there are none
        if(validResult.isEmpty()){
            //Get sanatized/validated data
            const {email, pass} = matchedData(req);

            //If we're proxied use passthrough IP
            const ip = config.proxied ? req.headers['x-forwarded-for'] : req.ip;

            //Check to make sure the user is logged in
            if(req.session.user == null){
                return errorHandler(res, "Invalid user!");
            }

            //Authenticate and find user model from DB
            const userDB = await userModel.authenticate(req.session.user.user, pass, "Bad password.");

            //If we have an invalid user
            if(userDB == null){
                return errorHandler(res, "Invalid user!");
            }

            if(userDB.email == email){
                return errorHandler(res, "Cannot set current email!");
            }


            //Look through DB and migration cache for existing email
            const existingDB = await userModel.findOne({email: new RegExp(email, 'i')});
            const needsMigration = userModel.migrationCache.emails.includes(email.toLowerCase());

            //If the email is in use
            if(existingDB != null || needsMigration){
                //Complain
                return errorHandler(res, "Email already in use!");
            }

            //Generate the password reset link
            const requestDB = await emailChangeModel.create({user: userDB._id, newEmail: email, ipHash: ip});

            //Don't wait on mailer to get back to the browser
            res.sendStatus(200);

            //Send the reset url via email
            await mailUtils.sendAddressVerification(requestDB, userDB, email);

            //Clean our hands of the operation
            return;
        }else{
            res.status(400);
            return res.send({errors: validResult.array()});
        }
    }catch(err){
        return exceptionHandler(res, err);
    }
}