'use strict';

var async = require('async');

exports.up = function(db, callback) {
    async.series([
        db.runSql.bind(db, 'START TRANSACTION;'),
        db.runSql.bind(db, 'ALTER TABLE users ADD COLUMN role VARCHAR(32)'),
        function migrateAdminFlag(done) {
            db.all('SELECT * FROM users ORDER BY createdAt', function (error, results) {
                if (error) return done(error);
                let ownerFound = false;

                async.eachSeries(results, function (user, next) {
                    let role;
                    if (!ownerFound && user.admin) {
                        role = 'owner';
                        ownerFound = true;
                        console.log(`Designating ${user.username} ${user.email} ${user.id} as the owner of this cloudron`);
                    } else {
                        role = user.admin ? 'admin' : 'user';
                    }
                    db.runSql('UPDATE users SET role=? WHERE id=?', [ role, user.id ], next);
                }, done);
            });
        },
        db.runSql.bind(db, 'ALTER TABLE users DROP COLUMN admin'),
        db.runSql.bind(db, 'ALTER TABLE users MODIFY role VARCHAR(32) NOT NULL'),
        db.runSql.bind(db, 'COMMIT')
    ], callback);
};

exports.down = function(db, callback) {
    db.runSql('ALTER TABLE users DROP COLUMN role', function (error) {
        if (error) console.error(error);

        callback(error);
    });
};

