"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get migrateDataInBatches () {
        return migrateDataInBatches;
    },
    get migrateDataInBatchesCommand () {
        return migrateDataInBatchesCommand;
    }
});
const _commander = require("commander");
const _createNamedLogger = require("@tamanu/shared/services/logging/createNamedLogger");
const _sleepAsync = require("@tamanu/utils/sleepAsync");
const _dataMigrations = /*#__PURE__*/ _interop_require_wildcard(require("./dataMigrations"));
const _database = require("../../database");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const migrateDataInBatches = async (name, { batchSize: batchSizeOverride, delay: delayOverrideMs })=>{
    // setup
    const DataMigration = _dataMigrations[name];
    if (!DataMigration) {
        throw new Error(`name not recognised: ${name}`);
    }
    const store = await (0, _database.initDatabase)({
        testMode: false
    });
    const batchSize = batchSizeOverride || DataMigration.defaultBatchSize;
    const delayMs = delayOverrideMs || DataMigration.defaultDelayMs;
    const log = (0, _createNamedLogger.createNamedLogger)('migrateData', {
        name,
        batchSize,
        delay: delayMs
    });
    const dm = new DataMigration(store, log);
    // run
    log.info('Started data migration');
    let total = 0;
    // eslint-disable-next-line no-constant-condition
    while(true){
        const num = await dm.doBatch(batchSize);
        if (typeof num !== 'number') {
            throw new Error('doBatch must return a number');
        }
        total += num;
        log.info('Migrated data batch', {
            num,
            total
        });
        if (dm.isComplete()) {
            break;
        }
        if (delayMs > 0) {
            await (0, _sleepAsync.sleepAsync)(delayMs);
        }
    }
    // done
    log.info('Completed data migration', {
        total
    });
    process.exit(0);
};
const names = Object.keys(_dataMigrations);
const migrateDataInBatchesCommand = new _commander.Command('migrateDataInBatches').description('Runs data migrations too big to be ordinary migrations; includes features that are necessary for long-running tasks, like batching and delays').option('-b, --batchSize <number>', 'Batch size for migrating data').option('-d, --delay <ms>', 'Delay in milliseconds between each batch').addArgument(new _commander.Argument('<name>', 'Name of the data migration').choices(names)).action(migrateDataInBatches);

//# sourceMappingURL=migrateDataInBatches.js.map