"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendPendingMails = exports.resetFailures = exports.deleteMail = exports.getPendingMails = exports.getMail = exports.enqueue = void 0;
const lodash_1 = __importDefault(require("lodash"));
const deep_extend_1 = __importDefault(require("deep-extend"));
const moment_1 = __importDefault(require("moment"));
const nodemailer_1 = require("nodemailer");
const config_1 = require("../config");
const database_1 = require("../db/database");
const logger_1 = __importDefault(require("../logger"));
const MailTemplateService = __importStar(require("./mailTemplateService"));
const Resources = __importStar(require("../utils/resources"));
const MAIL_QUEUE_DB_BATCH_SIZE = 50;
// TODO: Extract transporter into own module and initialize during main().
let transporterSingleton = null;
function transporter() {
    if (!transporterSingleton) {
        transporterSingleton = nodemailer_1.createTransport(deep_extend_1.default({}, config_1.config.server.email.smtp, {
            transport: 'smtp',
            pool: true
        }));
        MailTemplateService.configureTransporter(transporterSingleton);
    }
    return transporterSingleton;
}
async function sendMail(options) {
    logger_1.default
        .tag('mail', 'queue')
        .info('Sending pending mail[%d] of type %s. ' +
        'Had %d failures before.', options.id, options.email, options.failures);
    const renderedTemplate = await MailTemplateService.render(options);
    const mailOptions = {
        from: options.sender,
        to: options.recipient,
        subject: renderedTemplate.subject,
        html: renderedTemplate.body
    };
    await transporter().sendMail(mailOptions);
    logger_1.default.tag('mail', 'queue').info('Mail[%d] has been send.', options.id);
}
async function findPendingMailsBefore(beforeMoment, limit) {
    const rows = await database_1.db.all('SELECT * FROM email_queue WHERE modified_at < ? AND failures < ? ORDER BY id ASC LIMIT ?', [beforeMoment.unix(), 5, limit]);
    return lodash_1.default.map(rows, row => deep_extend_1.default({}, row, {
        data: JSON.parse(row.data)
    }));
}
async function removePendingMailFromQueue(id) {
    await database_1.db.run('DELETE FROM email_queue WHERE id = ?', [id]);
}
async function incrementFailureCounterForPendingEmail(id) {
    const now = moment_1.default();
    await database_1.db.run('UPDATE email_queue SET failures = failures + 1, modified_at = ? WHERE id = ?', [now.unix(), id]);
}
async function sendPendingMail(pendingMail) {
    try {
        await sendMail(pendingMail);
    }
    catch (error) {
        // we only log the error and increment the failure counter as we want to continue with pending mails
        logger_1.default.tag('mail', 'queue').error('Error sending pending mail[' + pendingMail.id + ']:', error);
        await incrementFailureCounterForPendingEmail(pendingMail.id);
        return;
    }
    await removePendingMailFromQueue(pendingMail.id);
}
async function doGetMail(id) {
    return await database_1.db.get('SELECT * FROM email_queue WHERE id = ?', [id]);
}
async function enqueue(sender, recipient, email, data) {
    if (!lodash_1.default.isPlainObject(data)) {
        throw new Error('Unexpected data: ' + data);
    }
    await database_1.db.run('INSERT INTO email_queue ' +
        '(failures, sender, recipient, email, data) ' +
        'VALUES (?, ?, ?, ?, ?)', [0, sender, recipient, email, JSON.stringify(data)]);
}
exports.enqueue = enqueue;
async function getMail(id) {
    return await doGetMail(id);
}
exports.getMail = getMail;
async function getPendingMails(restParams) {
    const row = await database_1.db.get('SELECT count(*) AS total FROM email_queue', []);
    const total = row.total;
    const filter = Resources.filterClause(restParams, 'id', ['id', 'failures', 'sender', 'recipient', 'email', 'created_at', 'modified_at'], ['id', 'failures', 'sender', 'recipient', 'email']);
    const mails = await database_1.db.all('SELECT * FROM email_queue WHERE ' + filter.query, lodash_1.default.concat([], filter.params));
    return {
        mails,
        total
    };
}
exports.getPendingMails = getPendingMails;
async function deleteMail(id) {
    await removePendingMailFromQueue(id);
}
exports.deleteMail = deleteMail;
async function resetFailures(id) {
    const statement = await database_1.db.run('UPDATE email_queue SET failures = 0, modified_at = ? WHERE id = ?', [moment_1.default().unix(), id]);
    if (!statement.changes) {
        throw new Error('Error: could not reset failure count for mail: ' + id);
    }
    return await doGetMail(id);
}
exports.resetFailures = resetFailures;
async function sendPendingMails() {
    logger_1.default.tag('mail', 'queue').debug('Start sending pending mails...');
    const startTime = moment_1.default();
    while (true) {
        logger_1.default.tag('mail', 'queue').debug('Sending next batch...');
        const pendingMails = await findPendingMailsBefore(startTime, MAIL_QUEUE_DB_BATCH_SIZE);
        if (lodash_1.default.isEmpty(pendingMails)) {
            logger_1.default.tag('mail', 'queue').debug('Done sending pending mails.');
            return;
        }
        for (const pendingMail of pendingMails) {
            await sendPendingMail(pendingMail);
        }
    }
}
exports.sendPendingMails = sendPendingMails;
//# sourceMappingURL=mailService.js.map