'use strict';

const async = require('async');

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE users ADD COLUMN creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP', function (error) {
        if (error) return callback(error);

        db.runSql('ALTER TABLE users ADD INDEX creationTime_index (creationTime)', function (error) {
            if (error) return callback(error);

            db.all('SELECT id, createdAt FROM users', function (error, results) {
                if (error) return callback(error);

                async.eachSeries(results, function (r, iteratorDone) {
                    const creationTime = new Date(r.createdAt);
                    db.runSql('UPDATE users SET creationTime=? WHERE id=?', [ creationTime, r.id ], iteratorDone);
                }, function (error) {
                    if (error) return callback(error);

                    db.runSql('ALTER TABLE users DROP COLUMN createdAt', callback);
                });
            });
        });
    });
};

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