'use strict';

var async = require('async');

// imports mailbox entries for existing users
exports.up = function(db, callback) {
    db.all('SELECT * FROM mailboxes', function (error, mailboxes) {
        async.eachSeries(mailboxes, function (mailbox, iteratorDone) {
            if (!mailbox.membersJson) return iteratorDone();

            let members = JSON.parse(mailbox.membersJson);
            members = members.map((m) => m && m.indexOf('@') === -1 ? `${m}@${mailbox.domain}` : m); // only because we don't do things in a xction

            db.runSql('UPDATE mailboxes SET membersJson=? WHERE name=? AND domain=?', [ JSON.stringify(members), mailbox.name, mailbox.domain ], iteratorDone);
        }, callback);
    });
};

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