"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWebSocketServer = void 0;
const ws_1 = __importDefault(require("ws"));
const websocket_gateway_1 = require("./websocket-gateway");
/**
 * Attaches a WebSocket server to the existing HTTP server and wires it to a
 * notification gateway. Returns the gateway so the application layer can use it
 * to send messages to connected devices, plus a close helper for graceful
 * shutdown.
 */
const createWebSocketServer = (options) => {
    const { httpServer, path = '/ws', logger } = options;
    const gateway = new websocket_gateway_1.WebSocketNotificationGateway(logger);
    const wss = new ws_1.default.Server({ server: httpServer, path });
    wss.on('connection', (socket) => {
        gateway.handleConnection(socket);
    });
    wss.on('error', (error) => {
        logger.error('[WebSocket] Server error', { error });
    });
    logger.info('[WebSocket] Server attached', { path });
    let isClosing = false;
    let closePromise;
    const close = () => {
        if (isClosing) {
            return closePromise ?? Promise.resolve();
        }
        isClosing = true;
        closePromise = new Promise((resolve) => {
            let timeout;
            const cleanup = () => {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = undefined;
                }
                wss.off('close', onClosed);
            };
            const onClosed = () => {
                cleanup();
                resolve();
            };
            timeout = setTimeout(() => {
                logger.warn('[WebSocket] Graceful close timed out; terminating remaining clients');
                for (const client of wss.clients) {
                    client.terminate();
                }
                onClosed();
            }, 3_000);
            wss.once('close', onClosed);
            try {
                wss.close();
            }
            catch (error) {
                logger.warn('[WebSocket] Error while closing server', { error });
                cleanup();
                resolve();
            }
        });
        return closePromise;
    };
    return { gateway, close };
};
exports.createWebSocketServer = createWebSocketServer;
//# sourceMappingURL=websocket-server.js.map