'use strict';

const async = require('async'),
    mail = require('../src/mail.js').default,
    safe = require('safetydance'),
    util = require('node:util');

// it seems some mail domains do not have dkimKey in the database for some reason because of some previous bad migration
exports.up = function(db, callback) {
    db.all('SELECT * FROM mail', [ ], function (error, mailDomains) {
        if (error) return callback(error);

        async.eachSeries(mailDomains, function (mailDomain, iteratorDone) {
            let dkimKey = safe.JSON.parse(mailDomain.dkimKeyJson);
            if (dkimKey && dkimKey.publicKey && dkimKey.privateKey) return iteratorDone();
            console.log(`${mailDomain.domain} has no dkim key in the database. generating a new one`);
            util.callbackify(mail.generateDkimKey)(function (error, dkimKey) {
                if (error) return iteratorDone(error);
                db.runSql('UPDATE mail SET dkimKeyJson=? WHERE domain=?', [ JSON.stringify(dkimKey), mailDomain.domain ], iteratorDone);
            });
        }, callback);
    });
};

exports.down = function(db, callback) {
    callback();
};
