'use strict';

var async = require('async');

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE apps ADD COLUMN reverseProxyConfigJson TEXT', function (error) {
        if (error) return callback(error);

        db.all('SELECT id, robotsTxt FROM apps', function (error, apps) {
            if (error) return callback(error);

            async.eachSeries(apps, function (app, iteratorDone) {
                if (!app.robotsTxt) return iteratorDone();

                db.runSql('UPDATE apps SET reverseProxyConfigJson=? WHERE id=?', [ JSON.stringify({ robotsTxt: JSON.stringify(app.robotsTxt) }), app.id ], iteratorDone);
            }, function (error) {
                if (error) return callback(error);

                db.runSql('ALTER TABLE apps DROP COLUMN robotsTxt', callback);
            });
        });
    });
};

exports.down = function(db, callback) {
    async.series([
        db.runSql.bind(db, 'ALTER TABLE apps DROP COLUMN reverseProxyConfigJson'),
    ], callback);
};

