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

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

    send(options) {
        options.from = `${config.app.senderName} <${config.app.senderEmail}>`;

        if (process.env.NODE_ENV !== 'production') {
            if (!config.smtp.auth.user)
                return Promise.resolve(true);

            options.to = config.app.senderEmail;
        }

        let error;
        return this.transporter.sendMail(options).catch(err => {
            error = err;

            throw err;
        }).finally(async() => {
            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 (receiver, replyTo, sent, subject, body, attachment, status)
                    VALUES (?, ?, 1, ?, ?, ?, ?)`, [
                options.to,
                options.replyTo,
                options.subject,
                options.text || options.html,
                fileNames,
                error && error.message || 'Sent'
            ]);
        });
    }
};