"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "createApp", {
    enumerable: true,
    get: function() {
        return createApp;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _dbNotifier = require("@tamanu/shared/services/dbNotifier");
const _constants = require("@tamanu/constants");
const _cache = require("@tamanu/settings/cache");
const _logging = require("@tamanu/shared/services/logging");
const _createApi = require("./createApi");
const _createWebsocket = require("./createWebsocket");
const _sync = require("./sync");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
async function createApp(ctx) {
    const api = await (0, _createApi.createApi)(ctx);
    const dbNotifier = await (0, _dbNotifier.defineDbNotifier)(ctx.store.sequelize.config, [
        _constants.NOTIFY_CHANNELS.TABLE_CHANGED
    ]);
    await (0, _sync.registerSyncLookupUpdateListener)(ctx.store.models, dbNotifier);
    (0, _cache.registerSettingsCacheInvalidator)(dbNotifier.listeners[_constants.NOTIFY_CHANNELS.TABLE_CHANGED]);
    dbNotifier.listeners[_constants.NOTIFY_CHANNELS.TABLE_CHANGED](async (payload)=>{
        if (payload.table !== 'settings') return;
        try {
            await ctx.aiService?.refreshContexts(ctx.settings);
        } catch (error) {
            _logging.log.warn({
                error
            }, 'Failed to refresh AI contexts after settings change');
        }
    });
    if (_config.default["socket.io"].enabled) {
        await (0, _createWebsocket.createWebsocket)(api.httpServer, ctx, dbNotifier);
    }
    // Release the connection back to the pool when the server is closed
    api.httpServer.on('close', ()=>{
        dbNotifier.close();
    });
    return {
        express: api.express,
        server: api.httpServer
    };
}

//# sourceMappingURL=createApp.js.map