"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "performDatabaseIntegrityChecks", {
    enumerable: true,
    get: function() {
        return performDatabaseIntegrityChecks;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _facts = require("@tamanu/constants/facts");
const _logging = require("@tamanu/shared/services/logging");
const _dataMigrations = require("@tamanu/database/dataMigrations");
const _selectFacilityIds = require("@tamanu/utils/selectFacilityIds");
const _sync = require("../sync");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
async function performDatabaseIntegrityChecks(context) {
    if (await (0, _dataMigrations.isSyncTriggerDisabled)(context.sequelize)) {
        throw Error('Sync Trigger is disabled in the database.');
    }
    // run in a transaction so any errors roll back all changes
    await context.sequelize.transaction(async ()=>{
        await ensureHostMatches(context);
        await ensureFacilityMatches(context);
    });
}
/*
 * ensureHostMatches
 */ async function ensureHostMatches(context) {
    const { LocalSystemFact } = context.models;
    const centralServer = new _sync.CentralServerConnection(context);
    const configuredHost = centralServer.host;
    const lastHost = await LocalSystemFact.get(_facts.FACT_CENTRAL_HOST);
    if (!lastHost) {
        await LocalSystemFact.set(_facts.FACT_CENTRAL_HOST, centralServer.host);
        return;
    }
    if (lastHost !== configuredHost) {
        throw new Error(`integrity check failed: sync.host mismatch: read ${configuredHost} from config, but already connected to ${lastHost} (you may need to drop and recreate the database, change the config back, or if you're 100% sure, remove the "syncHost" key from the "local_system_fact" table)`);
    }
}
/*
 * ensureFacilityMatches
 */ async function ensureFacilityMatches(context) {
    const { LocalSystemFact } = context.models;
    const configuredFacilities = (0, _selectFacilityIds.selectFacilityIds)(_config.default);
    const lastFacilities = await LocalSystemFact.get(_facts.FACT_FACILITY_IDS);
    if (lastFacilities) {
        // ensure both arrays contain the same set of facility ids
        const match = JSON.parse(lastFacilities).every((facilityId)=>configuredFacilities.includes(facilityId));
        if (!match) {
            // if the facility doesn't match, error
            throw new Error(`integrity check failed: serverFacilityId mismatch: read ${configuredFacilities} from config, but already registered as ${lastFacilities} (you may need to drop and recreate the database, change the config back, or if you're 100% sure, remove the "facilityIds" key from the "local_system_fact" table)`);
        }
    } else {
        const centralServer = new _sync.CentralServerConnection(context);
        _logging.log.info(`Verifying central server connection to ${centralServer.host}...`);
        await centralServer.connect();
        if (!centralServer.hasToken()) {
            throw new Error('Could not obtain valid token from central server.');
        }
        _logging.log.info('Verified central server connection');
        const facilityIdsString = JSON.stringify(configuredFacilities);
        await LocalSystemFact.set(_facts.FACT_FACILITY_IDS, facilityIdsString);
        _logging.log.info('Recorded facility IDs to database');
    }
}

//# sourceMappingURL=integrity.js.map