const nodemailer = require('nodemailer');
const smtpTransport = require("nodemailer-smtp-transport");

const ejs = require('ejs');

const path = require('path');
module.exports = class Email {
    constructor(user, url) {
        this.to = user.email;
        this.firstName = user.name.split(' ')[0];
        this.url = url;
        this.from = `SeoForLife support ${process.env.EMAIL_FROM}>`;
    }

    newTransport() {

        if (process.env.NODE_ENV === 'production') {
            // Sendgrid
            return nodemailer.createTransport(
                smtpTransport({
                    host: 'everest.pws-dns.net',
                    port: 465,
                    secure: true,
                    auth: {
                        user: 'support@seoforlife.ir',
                        pass: 'r]8yMWR@p~cz'
                    },
                    tls: {
                        rejectUnauthorized: false,
                    },
                })
            );
        }
console.log(`email host:${process.env.MRSEOS_EMAIL_HOST},port:${process.env.MRSEOS_EMAIL_PORT}`)
        return nodemailer.createTransport({
            host: process.env.MRSEOS_EMAIL_HOST,
            port: process.env.MRSEOS_EMAIL_PORT,
            auth: {
                user: process.env.MRSEOS_EMAIL_USERNAME,
                pass: process.env.MRSEOS_EMAIL_PASSWORD
            }
        });
    }

    // Send the actual email
    async send(template, subject) {
        // 1) Render HTML based on a pug template

        const pathRoot = path.dirname(require.main.filename || process.mainModule.filename);


        const html = await ejs.renderFile(`${pathRoot}/views/email/${template}.ejs`, {
            firstName: this.firstName,
            url: this.url,
            subject
        });
        // 2) Define email options
        const mailOptions = {
            from: this.from,
            to: this.to,
            subject,
            html,
        };

        // 3) Create a transport and send email
        await this.newTransport().sendMail(mailOptions, (err, info) => {
            if (err) {
                return console.log("err" + err);
            }
            console.log('info',info)
        });
    }

    async sendWelcome() {
        await this.send('welcome', 'Welcome to the MrSeos Family!');
    }

    async sendPasswordReset() {
        await this.send(
            'passwordReset',
            'Your password reset token (valid for only 10 minutes)'
        );
    }
    async sendVerifyEmail() {
        await this.send(
            'confirmEmail',
            'Your password reset token (valid for only 10 minutes)'
        );
    }
};