const nodemailer = require('nodemailer');
const cron = require('node-cron');
require('dotenv').config();

//  CONFIGURATION DE NODEMAILER 

if ( process.env.ENV == 'prod') {
    //  Mail support@technope.online
    var transporter = nodemailer.createTransport({    
        host: 'mail.technopet.online',
        port: 465,
        secure: true, //  True car notre serveur nécessite une connexion sécurisée (TLS)
        auth: {
            user: process.env.MAIL,
            pass: process.env.MAIL_PASSWORD,
        },
    });
}
else {
    //  Mail perso
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: process.env.MAIL_LOCAL,
          pass: process.env.MAIL_LOCAL_PASSWORD,
        },
    });
}



/**
 * Fonction qui envoie le mail à 8heure du matin
 *@param {Array} emailsToSend
 */
 const sendMailAt8hours = (emailsToSend) => {
    cron.schedule('0 8 * * *', () => {    
        console.log('Scheduling emails to be sent at 8 AM daily.');
        emailsToSend.forEach((email) => {
            sendEmail(email);
        });
    });
}

/**
 * Envoyer un mail
 * emailDetails = {
 *  recipient = string,
 *  subject = objet du mail,
 *  message = texte
 * }
 * 
 * @param {object} emailDetails 
 * @returns {boolean}
 */
const sendEmail = (emailDetails) => {  
    const MAIL = process.env.ENV == 'prod' ? process.env.MAIL : process.env.MAIL_LOCAL;

    const mailOptions = {
        from: MAIL,
        to: emailDetails.recipient,
        subject: emailDetails.subject,
        text: emailDetails.message,
    };

    if(process.env.ENV == 'prod') {
        transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error('Error sending email:', error);
            return true;
        } else {
            console.log('Email sent:', info.response);
            return false;
        }
        });
    }
    else {
        console.log(mailOptions);
        return true;
    }
}

  /**
 * Envoyer tous les mails dans le tableau d'objet mailDetail
 * @param { array } emailsToSend 
 */
const sendAllMails = (emailsToSend) => {
    for(let i = 0; i < emailsToSend.length; i++) {
        sendEmail(emailsToSend[i]);
    }
}

module.exports = {
    sendMailAt8hours,
    sendEmail,    
    sendAllMails,
}