'use strict';

const async = require('async'),
    safe = require('safetydance');

exports.up = function(db, callback) {
    db.all('SELECT * from domains', [], function (error, results) {
        if (error) return callback(error);

        async.eachSeries(results, function (r, iteratorDone) {
            if (!r.wellKnownJson) return iteratorDone();

            const wellKnown = safe.JSON.parse(r.wellKnownJson);
            if (!wellKnown || !wellKnown['matrix/server']) return iteratorDone();
            const matrixHostname = JSON.parse(wellKnown['matrix/server'])['m.server'];

            wellKnown['matrix/client'] = JSON.stringify({
                'm.homeserver': {
                    'base_url': 'https://' + matrixHostname
                }
            });

            db.runSql('UPDATE domains SET wellKnownJson=? WHERE domain=?', [ JSON.stringify(wellKnown), r.domain ], iteratorDone);
        }, callback);
    });
};

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