'use strict';

const async = require('async');

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE backups ADD COLUMN identifier VARCHAR(128)', function (error) {
        if (error) return callback(error);


        db.all('SELECT * FROM backups', function (error, backups) {
            if (error) return callback(error);

            async.eachSeries(backups, function (backup, next) {
                let identifier = 'unknown';

                if (backup.type === 'box') {
                    identifier = 'box';
                } else {
                    const match = backup.id.match(/app_(.+?)_.+/);
                    if (match) identifier = match[1];
                }

                db.runSql('UPDATE backups SET identifier=? WHERE id=?', [ identifier, backup.id ], next);
            }, function (error) {
                if (error) return callback(error);

                db.runSql('ALTER TABLE backups MODIFY COLUMN identifier VARCHAR(128) NOT NULL', callback);
            });
        });
    });
};

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