const nodemailer = require("nodemailer");
require('dotenv').config();

//const { google } = require("googleapis");
//const OAuth2 = google.auth.OAuth2;

module.exports = {


    friendlyName: 'Send Smtp',


    description: '',


    inputs: {
        subject: {
            type: 'string',
            required: true
        },
        to: {
            type: 'string',
            required: true
        },
        text: {
            type: 'string',
            required: true
        }
    },

    exits: {
        success: {
            description: 'Success',

        },
        mailSendingFailed: {
            message: "Mail sending failed"
        }
    },


    fn: async function ({ to, subject, text }, exits) {

        //let testAccount = await nodemailer.createTestAccount();

        // create reusable transporter object using the default SMTP transport
        let transporter = nodemailer.createTransport({
            host: process.env.MAIL_HOST,//"smtp.ethereal.email",
            port: process.env.MAIL_PORT,//587,
            secure: process.env.MAIL_SECURE, // true for 465, false for other ports
            auth: {
                user: process.env.MAIL_USER,//testAccount.user, // generated ethereal user
                pass: process.env.MAIL_PASS//testAccount.pass, // generated ethereal password
            },
        });

        /*let info = await transporter.sendMail({
            from: '"Fred Foo 👻" <foo@example.com>', // sender address
            to: "bar@example.com, baz@example.com", // list of receivers
            subject: "Hello ✔", // Subject line
            text: "Hello world?", // plain text body
            html: "<b>Hello world?</b>", // html body
        });*/


        const mailOptions = {
            from: process.env.MAIL_FROM,
            to,
            subject,
            generateTextFromHTML: true,
            html: `<div>${text}</div>`
        };
        let status = false
        await transporter.sendMail(mailOptions, async function (err, data) {
            if (err) {
                throw { mailSendingFailed: { message: 'Mail sending failed' } }
            }
            status = true
            console.log('Mail sended', data)
            await transporter.close()
        })
        return exits.success({ Done: status })
    }
};

