"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 startApiCommand () {
        return startApiCommand;
    },
    get startSyncCommand () {
        return startSyncCommand;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _commander = require("commander");
const _logging = require("@tamanu/shared/services/logging");
const _timeZoneCheck = require("@tamanu/shared/utils/timeZoneCheck");
const _selectFacilityIds = require("@tamanu/utils/selectFacilityIds");
const _constants = require("@tamanu/constants");
const _checkConfig = require("../checkConfig");
const _utils = require("@tamanu/shared/utils");
const _initTimesync = require("../services/initTimesync");
const _database = require("../database");
const _sync = require("../sync");
const _createApiApp = require("../createApiApp");
const _serverInfo = require("../serverInfo");
const _ApplicationContext = require("../ApplicationContext");
const _createSyncApp = require("../createSyncApp");
const _startTasks = require("./startTasks");
const _SyncTask = require("../tasks/SyncTask");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const APP_TYPES = {
    API: 'api',
    SYNC: 'sync'
};
const startApp = (appType)=>async ({ skipMigrationCheck })=>{
        _logging.log.info(`Starting facility ${appType} server version ${_serverInfo.version}`, {
            serverFacilityIds: (0, _selectFacilityIds.selectFacilityIds)(_config.default)
        });
        _logging.log.info(`Process info`, {
            execArgs: process.execArgs || '<empty>'
        });
        const context = await new _ApplicationContext.ApplicationContext().init({
            appType
        });
        await (0, _database.prepareDatabaseForStartup)(context, {
            skipMigrationCheck
        });
        await (0, _utils.initDeviceId)({
            context,
            deviceType: _constants.DEVICE_TYPES.FACILITY_SERVER
        });
        await (0, _checkConfig.checkConfig)(context);
        await (0, _database.performDatabaseIntegrityChecks)(context);
        context.timesync = await (0, _initTimesync.initTimesync)({
            models: context.models,
            url: `${_config.default.sync.host.trim().replace(/\/*$/, '')}/api/timesync`
        });
        if (appType === APP_TYPES.API) {
            context.syncConnection = new _sync.FacilitySyncConnection();
        } else {
            context.centralServer = new _sync.CentralServerConnection(context);
            context.syncManager = new _sync.FacilitySyncManager(context);
        }
        await (0, _timeZoneCheck.performTimeZoneChecks)({
            remote: context.centralServer,
            sequelize: context.sequelize,
            config: _config.default
        });
        let server, port;
        switch(appType){
            case APP_TYPES.API:
                ({ server } = await (0, _createApiApp.createApiApp)(context));
                ({ port } = _config.default);
                break;
            case APP_TYPES.SYNC:
                ({ server } = await (0, _createSyncApp.createSyncApp)(context));
                ({ port } = _config.default.sync.syncApiConnection);
                // start SyncTask as part of sync app so that it is in the same process with tamanu-sync process
                (0, _startTasks.startTasks)({
                    skipMigrationCheck: false,
                    taskClasses: [
                        _SyncTask.SyncTask
                    ],
                    syncManager: context.syncManager
                });
                break;
            default:
                throw new Error(`Unknown app type: ${appType}`);
        }
        if (+process.env.PORT) {
            port = +process.env.PORT;
        }
        server.listen(port, ()=>{
            _logging.log.info(`Server is running on port ${port}!`);
        });
        process.once('SIGTERM', ()=>{
            _logging.log.info('Received SIGTERM, closing HTTP server');
            server.close();
        });
    };
const startApiCommand = new _commander.Command('startApi').description('Start the Tamanu Facility API server').option('--skipMigrationCheck', 'skip the migration check on startup').action(startApp(APP_TYPES.API));
const startSyncCommand = new _commander.Command('startSync').description('Start the Tamanu Facility SYNC server').option('--skipMigrationCheck', 'skip the migration check on startup').action(startApp(APP_TYPES.SYNC));

//# sourceMappingURL=startApp.js.map