'use strict';

let async = require('async');

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE tasks CHANGE errorMessage errorJson TEXT', [], function (error) {
        if (error) console.error(error);

        // convert error messages into json
        db.all('SELECT id, errorJson FROM apps', function (error, apps) {
            async.eachSeries(apps, function (app, iteratorDone) {
                if (app.errorJson === 'null') return iteratorDone();
                if (app.errorJson === null) return iteratorDone();

                db.runSql('UPDATE apps SET errorJson = ? WHERE id = ?', [ JSON.stringify({ message: app.errorJson }), app.id ], iteratorDone);
            }, callback);
        });
    });
};

exports.down = function(db, callback) {
    db.runSql('ALTER TABLE tasks CHANGE errorJson errorMessage TEXT', [], function (error) {
        if (error) console.error(error);
        callback(error);
    });
};
