"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 DatabaseIncompatibleError () {
        return DatabaseIncompatibleError;
    },
    get syncDatabaseServerVersion () {
        return syncDatabaseServerVersion;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _semver = /*#__PURE__*/ _interop_require_default(require("semver"));
const _constants = require("@tamanu/constants");
const _logging = require("@tamanu/shared/services/logging");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function getShouldBypass() {
    if (_config.default.db?.skipVersionCompatibilityCheck === true) {
        return {
            shouldBypass: true,
            reason: 'db.skipVersionCompatibilityCheck is enabled'
        };
    }
    if (process.env.NODE_ENV !== 'production') {
        return {
            shouldBypass: true,
            reason: `NODE_ENV is "${process.env.NODE_ENV ?? '<unset>'}" (not "production")`
        };
    }
    return {
        shouldBypass: false,
        reason: null
    };
}
// Returns the stored version, or null if it's missing or not valid semver (e.g. the legacy 'unknown').
function normalizeStoredVersion(stored) {
    return _semver.default.valid(stored);
}
function resolveServerVersion(serverVersion) {
    const globalServerInfo = globalThis.serverInfo;
    const version = serverVersion ?? globalServerInfo?.version;
    if (!version) {
        throw new Error('serverVersion is required for the database version compatibility check in production');
    }
    if (_semver.default.valid(version) === null) {
        throw new Error(`serverVersion "${version}" is not a valid semver version`);
    }
    return version;
}
let DatabaseIncompatibleError = class DatabaseIncompatibleError extends Error {
    constructor(storedVersion, serverVersion){
        super(`Database version compatibility check failed. Database has been used with v${storedVersion}, but this server is v${serverVersion}.` + '\n\nThis could mean there’s been a partial rollback after an aborted upgrade. Possible recovery steps:' + `\n\n- if you’re confident the database is compatible, manually update the currentVersion row in local_system_facts to ${serverVersion};` + '\n- set db.skipVersionCompatibilityCheck to true in config (not recommended).\n'), _define_property(this, "storedVersion", void 0), _define_property(this, "serverVersion", void 0);
        this.name = 'DatabaseIncompatibleError';
        this.storedVersion = storedVersion;
        this.serverVersion = serverVersion;
    }
};
async function syncDatabaseServerVersion({ models, serverVersion, checkOnly = false }) {
    const { shouldBypass, reason } = getShouldBypass();
    if (shouldBypass) {
        _logging.log.warn('Bypassing database version compatibility check', {
            reason
        });
        return;
    }
    const resolvedServerVersion = resolveServerVersion(serverVersion);
    const { LocalSystemFact } = models;
    const stored = normalizeStoredVersion(await LocalSystemFact.get(_constants.FACT_CURRENT_VERSION));
    if (!stored) {
        if (!checkOnly) {
            await LocalSystemFact.set(_constants.FACT_CURRENT_VERSION, resolvedServerVersion);
        }
        return;
    }
    const comparison = _semver.default.compare(stored, resolvedServerVersion);
    if (comparison > 0) {
        _logging.log.error('Refusing startup; database migration state is ahead of what server expects.');
        throw new DatabaseIncompatibleError(stored, resolvedServerVersion);
    }
    if (!checkOnly && comparison < 0) {
        await LocalSystemFact.set(_constants.FACT_CURRENT_VERSION, resolvedServerVersion);
    }
}

//# sourceMappingURL=databaseVersionCompatibility.js.map