'use strict';

let async = require('async');

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE apps MODIFY mailboxDomain VARCHAR(128)', [], function (error) { // make it nullable
        if (error) console.error(error);

        // clear mailboxName/Domain for apps that do not use mail addons
        db.all('SELECT * FROM apps', function (error, apps) {
            if (error) return callback(error);

            async.eachSeries(apps, function (app, iteratorDone) {
                var manifest = JSON.parse(app.manifestJson);
                if (manifest.addons['sendmail'] || manifest.addons['recvmail']) return iteratorDone();

                db.runSql('UPDATE apps SET mailboxName=?, mailboxDomain=? WHERE id=?', [ null, null, app.id ], iteratorDone);
            }, callback);
        });
    });
};

exports.down = function(db, callback) {
    db.runSql('ALTER TABLE apps MODIFY manifestJson VARCHAR(128) NOT NULL', [], function (error) {
        if (error) console.error(error);
        callback(error);
    });
};
