"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createQuorumBridgeCallback = createQuorumBridgeCallback;
exports.getActiveCallback = getActiveCallback;
exports.startQuorumBridge = startQuorumBridge;
const events_1 = require("../../lib/events");
const logger_1 = require("../../lib/logger");
/**
 * Bridge HotMesh quorum messages to the NATS event system.
 *
 * Subscribes to a HotMesh engine's quorum channel via `subQuorum()`
 * and republishes each message as an `LTEvent` on `lt.mesh.{type}`.
 *
 * Topic mapping (quorum subscription receives these types):
 *   quorum type "pong"     → lt.events.mesh.pong
 *   quorum type "ping"     → lt.events.mesh.ping
 *   quorum type "job"      → lt.events.mesh.job
 *   quorum type "work"     → lt.events.mesh.work
 *   quorum type "activate" → lt.events.mesh.activate
 *   quorum type "cron"     → lt.events.mesh.cron
 *   quorum type "user"     → lt.events.mesh.user
 *
 * Note: throttle commands don't echo through the quorum subscription.
 * The throttle route publishes a synthetic event directly to NATS.
 */
let activeCallback = null;
/**
 * Create a quorum callback that republishes messages to NATS.
 */
function createQuorumBridgeCallback(appId) {
    const callback = (_topic, message) => {
        const type = message.type || 'unknown';
        const event = {
            type: `mesh.${type}`,
            source: 'controlplane',
            workflowId: message.guid || '',
            workflowName: '',
            taskQueue: appId,
            data: message,
            timestamp: new Date().toISOString(),
        };
        events_1.eventRegistry.publish(event).catch(() => {
            // fire-and-forget — NATS publish failures are non-critical
        });
    };
    activeCallback = callback;
    return callback;
}
/**
 * Get the active quorum bridge callback (for unsubscription).
 */
function getActiveCallback() {
    return activeCallback;
}
/**
 * Start the quorum bridge for a given HotMesh engine.
 */
async function startQuorumBridge(engine, appId) {
    const callback = createQuorumBridgeCallback(appId);
    await engine.subQuorum(callback);
    logger_1.loggerRegistry.info(`[controlplane] quorum bridge active for ${appId} → lt.mesh.*`);
}
