const nodemailer = require('nodemailer');
const config = require('./config');
const db = require('./database');

module.exports = {
    init() {
        if (!this.transporter)
            this.transporter = nodemailer.createTransport(config.smtp);
    },

    async send(options) {
        options.from = `${config.app.senderName} <${config.app.senderEmail}>`;
        const env = process.env.NODE_ENV;
        const canSend = env === 'production' || !env || options.force;

        if (!canSend || !config.smtp.auth.user) {
            const notProductionError = {message: 'This not production, this email not sended'};
            await this.mailLog(options, notProductionError);
            return Promise.resolve(true);
        }

        if (!env)
            options.to = config.app.senderEmail;

        let res;
        let error;
        try {
            res = await this.transporter.sendMail(options);
        } catch (err) {
            error = err;
            throw err;
        } finally {
            await this.mailLog(options, error);
        }

        return res;
    },

    async mailLog(options, error) {
        const attachments = [];
        if (options.attachments) {
            for (let attachment of options.attachments) {
                const fileName = attachment.filename;
                const filePath = attachment.path;
                if (fileName.includes('.png')) continue;

                if (fileName || filePath)
                    attachments.push(filePath ? filePath : fileName);
            }
        }

        const fileNames = attachments.join(',\n');

        await db.rawSql(`
            INSERT INTO vn.mail
                SET receiver = ?,
                    replyTo = ?,
                    sent = ?,
                    subject = ?,
                    body = ?,
                    attachment = ?,
                    status = ?`, [
            options.to,
            options.replyTo,
            error ? 2 : 1,
            options.subject,
            options.text || options.html,
            fileNames,
            error && error.message || 'OK'
        ]);
    }

};