"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ServerHost", {
    enumerable: true,
    get: function() {
        return ServerHost;
    }
});
const _express = /*#__PURE__*/ _interop_require_default(require("express"));
const _connecthistoryapifallback = /*#__PURE__*/ _interop_require_default(require("connect-history-api-fallback"));
const _nodepath = require("node:path");
const _serverenv = require("./server.env");
const _runtimeexceptions = require("./exceptions/runtime.exceptions");
const _serverconstants = require("./server.constants");
const _fsutils = require("./utils/fs.utils");
const _loadcontrollers = require("./shared/load-controllers");
const _swagger = require("./utils/swagger/swagger");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
class ServerHost {
    configService;
    bootTask;
    socketIoGateway;
    typeormService;
    exceptionFilter;
    logger;
    constructor(loggerFactory, configService, bootTask, socketIoGateway, typeormService, exceptionFilter){
        this.configService = configService;
        this.bootTask = bootTask;
        this.socketIoGateway = socketIoGateway;
        this.typeormService = typeormService;
        this.exceptionFilter = exceptionFilter;
        this.logger = loggerFactory(ServerHost.name);
    }
    async boot(app, quick_boot = false, listenRequests = true) {
        await this.serveControllerRoutes(app);
        if (!quick_boot) {
            await this.bootTask.runOnce();
        }
        if (listenRequests) return this.httpListen(app);
    }
    hasConnected() {
        return this.typeormService.hasConnected();
    }
    async serveControllerRoutes(app) {
        const swaggerDisabled = process.env[_serverconstants.AppConstants.DISABLE_SWAGGER_OPENAPI] === "true";
        app.use((req, res, next)=>{
            if (!req.originalUrl.startsWith("/metrics") && !req.originalUrl.startsWith("/api") && !req.originalUrl.startsWith("/api-docs") && !req.originalUrl.startsWith("/socket.io")) {
                (0, _connecthistoryapifallback.default)()(req, res, next);
            } else {
                next();
            }
        }).use((0, _loadcontrollers.loadControllersFunc)());
        if (swaggerDisabled) {
            this.logger.log("Swagger/OpenAPI documentation disabled");
        } else {
            await (0, _swagger.setupSwagger)(app, this.logger);
            this.logger.log("Swagger/OpenAPI documentation enabled");
        }
        const bundleDistPath = (0, _nodepath.join)((0, _fsutils.superRootPath)(), _serverconstants.AppConstants.defaultClientBundleStorage, "dist");
        const backupClientPath = (0, _nodepath.join)((0, _fsutils.superRootPath)(), "node_modules", _serverconstants.AppConstants.clientPackageName, "dist");
        app.use(_express.default.static(bundleDistPath));
        app.use(_express.default.static(backupClientPath));
        app.get("*", (req, _)=>{
            const path = req.originalUrl;
            let resource = "MVC";
            if (path.startsWith("/socket.io") || path.startsWith("/api") || path.startsWith("/metrics") || path.startsWith("/api-docs")) {
                resource = "API";
            } else if (path.endsWith(".min.js")) {
                resource = "client-bundle";
            }
            this.logger.error(`${resource} resource at '${path}' was not found`);
            if (!path.startsWith("/socket.io")) {
                throw new _runtimeexceptions.NotFoundException(`${resource} resource was not found`, path);
            }
        });
        app.use(this.exceptionFilter.handle.bind(this.exceptionFilter));
    }
    async httpListen(app) {
        const port = (0, _serverenv.fetchServerPort)();
        if (!port || Number.isNaN(Number.parseInt(port))) {
            throw new Error("The FDM Server requires a numeric port input argument to run");
        }
        const swaggerDisabled = process.env[_serverconstants.AppConstants.DISABLE_SWAGGER_OPENAPI] === "true";
        const hostOrFqdn = "0.0.0.0";
        const server = app.listen(Number.parseInt(port), hostOrFqdn, ()=>{
            this.logger.log(`Server started... open it at http://127.0.0.1:${port}`);
            if (!swaggerDisabled) {
                this.logger.log(`API Documentation available at http://127.0.0.1:${port}/api-docs`);
            }
        });
        this.socketIoGateway.attachServer(server);
    }
}

//# sourceMappingURL=server.host.js.map