/*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 nodeMailer = require("nodemailer");
const validator = require('validator');

//local imports
const loggerUtils = require('./loggerUtils');


//Setup mail transport
/**
 * nodemailer transport object, generated from options specific in our config file
 */
const transporter = nodeMailer.createTransport({
    host: config.mail.host,
    port: config.mail.port,
    secure: config.mail.secure,
    auth: {
        user: config.mail.address,
        pass: config.mail.pass
    }
});

/**
 * Sends an email as tokebot to the requested user w/ the requested body and signature
 * @param {String} to - String containing the email address to send to
 * @param {String} subject - Subject line of the email to send
 * @param {String} body - Body contents, either HTML or Plaintext
 * @param {Boolean} htmlBody - Whether or not Body contents should be sent as HTML or Plaintext
 * @returns {Object} Sent mail info
 */
module.exports.mailem = async function(to, subject, body, htmlBody = false){
    try{
        //If we have a bad email address
        if(!validator.isEmail(to)){
            //fuck off
            return;
        }

        //Create mail object
        const mailObj = {
            from: `"Tokebot🤖💨"<${config.mail.address}>`,
            to,
            subject
        };

        //If we're sending HTML
        if(htmlBody){
            //set body as html
            mailObj.html = body;
        //If we're sending plaintext
        }else{
            //Set body as plaintext
            mailObj.text = body
        }

        //Send mail based on mail object
        const sentMail = await transporter.sendMail(mailObj);

        //return the mail info
        return sentMail;
    }catch(err){
        loggerUtils.dumpError(err, new Date(), 'crash/mail/');
    }
}

/**
 * Sends address verification email
 * @param {Mongoose.Document} requestDB - DB Document Object for the current email change request token
 * @param {Mongoose.Document} userDB - DB Document Object for the user we're verifying email against
 * @param {String} newEmail - New email address to send to
 * @param {Boolean} newUser - Denotes an email going out to a new account
 * @param {Boolean} migration - Denotes an email going out to an account which was just mirated
 */
module.exports.sendAddressVerification = async function(requestDB, userDB, newEmail, newUser = false, migration = false,){
    let subject = `Email Change Request - ${userDB.user}`;
    let content = `<h1>email change request</h1>
        <p>a request to change the email associated with the ${config.instanceName} account '${userDB.user}' to this address has been requested.<br>
        <a href="${requestDB.getChangeURL()}">click here</a> to confirm this change.</p>
        <sup>if you received this email without request, feel free to ignore and delete it! -tokebot</sup>`;
    
    if(newUser){
        subject = `New User Email Confirmation - ${userDB.user}`;

        content = `<h1>New user email confirmation</h1>
        <p>a new ${config.instanceName} account '${userDB.user}' was created with this email address.<br>
        <a href="${requestDB.getChangeURL()}">click here</a> to confirm this change.</p>
        <sup>if you received this email without request, feel free to ignore and delete it! -tokebot</sup>`;
    }

    if(migration){
        subject = `User Migration Email Confirmation - ${userDB.user}`;

        content = `<h1>User migration email confirmation</h1>
        <p>The ${config.instanceName} account '${userDB.user}' was successfully migrated to our <a href="https://git.ourfore.st/rainbownapkin/canopy">fancy new codebase</a>.<br>
        <a href="${requestDB.getChangeURL()}">click here</a> to confirm this change.</p> 
        <sup>if you received this email without request, reach out to an admin, as your old account might be getting jacked! -tokebot</sup>`;
    }


    //Send the reset url via email
    await module.exports.mailem(
        newEmail,
        subject,
        content,
        true
    );

    //If the user has a pre-existing email address
    if(userDB.email != null && userDB.email != ""){
        await module.exports.mailem(
            userDB.email,
            `Email Change Request - ${userDB.user}`,
            `<h1>Email Change Request Notification</h1>
            <p>A request to change the email associated with the ${config.instanceName} account '${userDB.user}' to another address has been requested.<br>
            <sup>If you received this email without request, you should <strong>immediately</strong> change your password and contact the server adminsitrator! -Tokebot</sup>`,
            true
        );
    }
}