"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createServer = createServer;
const fastify_1 = __importDefault(require("fastify"));
const core_plugin_1 = __importDefault(require("./plugins/core.plugin"));
const error_handler_plugin_1 = require("./plugins/error-handler.plugin");
const request_id_plugin_1 = __importDefault(require("./plugins/request-id.plugin"));
const routes_plugin_1 = __importDefault(require("./plugins/routes.plugin"));
const static_plugin_1 = __importDefault(require("./plugins/static.plugin"));
const success_handle_plugin_1 = __importDefault(require("./plugins/success-handle.plugin"));
const ws_plugin_1 = __importDefault(require("./plugins/ws/ws.plugin"));
const api_client_plugin_1 = __importDefault(require("./plugins/api-client.plugin"));
const nginx_plugin_1 = __importDefault(require("./plugins/nginx.plugin"));
const env_1 = require("./env");
function normalizeLogLevel(v) {
    const lv = (v ?? "").toLowerCase().trim();
    if (!lv)
        return undefined;
    if (["fatal", "error", "warn", "info", "debug", "trace", "silent"].includes(lv))
        return lv;
    return "info";
}
function createFastifyLogger() {
    const level = normalizeLogLevel(env_1.env.logLevel);
    if (process.env.NGM_DEBUG === '1') {
        console.log(`Logger initialized with level: ${level || 'silent (disabled)'}`);
    }
    if (!level)
        return false;
    return { level };
}
async function createServer() {
    const fastify = (0, fastify_1.default)({
        logger: createFastifyLogger(),
        genReqId: (req) => {
            const hdr = req.headers["x-request-id"];
            if (typeof hdr === "string" && hdr.trim())
                return hdr.trim();
            return crypto.randomUUID();
        }
    });
    await fastify.register(request_id_plugin_1.default);
    await fastify.register(error_handler_plugin_1.errorHandlerPlugin);
    await fastify.register(success_handle_plugin_1.default);
    await fastify.register(core_plugin_1.default);
    await fastify.register(nginx_plugin_1.default);
    await fastify.register(ws_plugin_1.default);
    await fastify.register(api_client_plugin_1.default);
    await fastify.register(routes_plugin_1.default);
    await fastify.register(static_plugin_1.default);
    fastify.addHook('onClose', async () => {
        await fastify.core.dispose?.();
        fastify.log.info('Server is closing, performing cleanup...');
    });
    return fastify;
}
