'use strict';

const _ = require('../src/underscore.js').default;

exports.up = async function(db) {
    const result = await db.runSql('SELECT * FROM settings WHERE name=?', [ 'backup_config' ]);
    if (!result.length) return;

    const backupConfig = JSON.parse(result[0].value);
    // split policy, limits from backupConfig
    const backupPolicy = backupConfig.schedulePattern && backupConfig.retentionPolicy ? { schedule: backupConfig.schedulePattern, retention: backupConfig.retentionPolicy } : null;

    const storageConfig = _.omit(backupConfig, ['copyConcurrency', 'syncConcurrency', 'memoryLimit', 'downloadConcurrency',
        'deleteConcurrency', 'uploadPartSize', 'schedulePattern', 'retentionPolicy', 'mountStatus']);
    const limits = _.pick(backupConfig, ['copyConcurrency', 'syncConcurrency', 'memoryLimit', 'downloadConcurrency',
        'deleteConcurrency', 'uploadPartSize']);

    await db.runSql('START TRANSACTION');
    await db.runSql('UPDATE settings SET value=?,name=? WHERE name=?', [ JSON.stringify(storageConfig), 'backup_storage', 'backup_config']); // rename
    if (backupPolicy) {
        await db.runSql('INSERT INTO settings (name, value) VALUES (?, ?)', [ 'backup_policy', JSON.stringify(backupPolicy) ]);
    }
    await db.runSql('INSERT INTO settings (name, value) VALUES (?, ?)', [ 'backup_limits', JSON.stringify(limits) ]);
    await db.runSql('COMMIT');
};

exports.down = async function(/* db */) {
};
