'use strict';

const async = require('async'),
    hat = require('../src/hat.js').default;

exports.up = function(db, callback) {
    db.all('SELECT * from backups', function (error, allBackups) {
        if (error) return callback(error);

        console.log(`Fixing up ${allBackups.length} backup entries`);
        const idMap = {};
        allBackups.forEach(b => {
            b.remotePath = b.id;
            b.id = `${b.type}_${b.identifier}_v${b.packageVersion}_${hat(256)}`; // id is used by the UI to derive dependent packages. making this a UUID will require a lot of db querying
            idMap[b.remotePath] = b.id;
        });

        db.runSql('ALTER TABLE backups ADD COLUMN remotePath VARCHAR(256)', function (error) {
            if (error) return callback(error);

            db.runSql('ALTER TABLE backups CHANGE COLUMN dependsOn dependsOnJson TEXT', function (error) {
                if (error) return callback(error);

                async.eachSeries(allBackups, function (backup, iteratorDone) {
                    const dependsOnPaths = backup.dependsOn ? backup.dependsOn.split(',') : []; // previously, it was paths
                    let dependsOnIds = [];
                    dependsOnPaths.forEach(p => { if (idMap[p]) dependsOnIds.push(idMap[p]); });

                    db.runSql('UPDATE backups SET id = ?, remotePath = ?, dependsOnJson = ? WHERE id = ?', [ backup.id, backup.remotePath, JSON.stringify(dependsOnIds), backup.remotePath ], iteratorDone);
                }, function (error) {
                    if (error) return callback(error);

                    db.runSql('ALTER TABLE backups MODIFY COLUMN remotePath VARCHAR(256) NOT NULL UNIQUE', callback);
                });
            });
        });
    });
};

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

        db.runSql('ALTER TABLE backups RENAME COLUMN dependsOnJson to dependsOn', function (error) {
            if (error) return callback(error);

            callback(error);
        });
    });
};

