"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.listApps = listApps;
exports.rollCall = rollCall;
exports.applyThrottle = applyThrottle;
exports.getStreamStats = getStreamStats;
exports.subscribeMesh = subscribeMesh;
exports.listStreamMessages = listStreamMessages;
const controlplane = __importStar(require("../services/controlplane"));
const events_1 = require("../lib/events");
/**
 * List all registered application namespaces.
 *
 * @returns `{ status: 200, data: { apps } }` array of known app identifiers
 */
async function listApps() {
    try {
        const apps = await controlplane.listApps();
        return { status: 200, data: { apps } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Query active worker profiles for an application.
 *
 * Sends a roll-call request to the mesh and collects responses from
 * all running workers within the optional delay window.
 *
 * @param input.appId — application namespace to query (defaults to 'durable')
 * @param input.delay — milliseconds to wait for worker responses before returning
 * @returns `{ status: 200, data: { profiles } }` array of worker profile objects
 */
async function rollCall(input) {
    try {
        const appId = input.appId || 'durable';
        const profiles = await controlplane.rollCall(appId, input.delay);
        return { status: 200, data: { profiles } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Apply a throttle rate to workflow execution.
 *
 * Sets the throttle value for a specific topic or workflow within an app
 * namespace. Also publishes a synthetic `mesh.throttle` event so the
 * dashboard event stream reflects the change.
 *
 * @param input.appId — application namespace (defaults to 'durable')
 * @param input.throttle — throttle value to apply (required, must be a number)
 * @param input.topic — optional topic to scope the throttle to
 * @param input.guid — optional workflow GUID to scope the throttle to
 * @returns `{ status: 200, data: { success } }` boolean indicating the throttle was applied
 */
async function applyThrottle(input) {
    try {
        const appId = input.appId || 'durable';
        if (typeof input.throttle !== 'number') {
            return { status: 400, error: 'throttle (number) is required' };
        }
        const result = await controlplane.applyThrottle(appId, {
            throttle: input.throttle,
            topic: input.topic,
            guid: input.guid,
            scope: input.scope,
        });
        // Publish a synthetic event so the dashboard event stream sees it
        const throttleEvent = {
            type: 'mesh.throttle',
            source: 'controlplane',
            workflowId: input.guid || '',
            workflowName: '',
            taskQueue: appId,
            data: { throttle: input.throttle, topic: input.topic, guid: input.guid, appId },
            timestamp: new Date().toISOString(),
        };
        events_1.eventRegistry.publish(throttleEvent).catch(() => { });
        return { status: 200, data: { success: result } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Retrieve stream statistics for an application.
 *
 * Returns throughput and backlog metrics for Redis streams backing the
 * given app namespace over the specified time window.
 *
 * @param input.app_id — application namespace (defaults to 'durable')
 * @param input.duration — time window for stats aggregation, e.g. '1h', '30m' (defaults to '1h')
 * @param input.stream — optional specific stream name to filter results
 * @returns `{ status: 200, data: { ... } }` stream statistics object
 */
async function getStreamStats(input) {
    try {
        const schema = input.app_id || 'durable';
        const duration = input.duration || '1h';
        const stats = await controlplane.getStreamStats(schema, duration, input.stream);
        return { status: 200, data: stats };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Subscribe to mesh events for an application.
 *
 * Establishes a subscription to the event stream of the given app
 * namespace so that mesh events are captured and forwarded.
 *
 * @param input.appId — application namespace to subscribe to (defaults to 'durable')
 * @returns `{ status: 200, data: { subscribed, appId } }` confirmation with the subscribed app ID
 */
async function subscribeMesh(input) {
    try {
        const appId = input.appId || 'durable';
        await controlplane.subscribeMesh(appId);
        return { status: 200, data: { subscribed: true, appId } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Browse stream messages across engine and worker streams.
 *
 * Returns paginated, filterable, sortable results from the Postgres
 * engine_streams and worker_streams tables. Messages are schema-isolated
 * by namespace.
 *
 * @param input.namespace — Postgres schema (required, e.g. "durable")
 * @param input.limit — page size (1–100, default 25)
 * @param input.offset — pagination offset (default 0)
 * @param input.sort_by — sort column: created_at, stream_name, priority, id
 * @param input.order — sort direction: asc | desc (default desc)
 * @param input.source — filter by source: engine | worker (default all)
 * @param input.status — filter by status: pending | claimed | processed | dead_lettered
 * @param input.stream_name — partial match on stream name (ILIKE)
 * @param input.msg_type — filter by message type (worker streams only)
 */
async function listStreamMessages(input) {
    try {
        if (!input.namespace) {
            return { status: 400, error: 'namespace is required' };
        }
        if (input.source !== 'engine' && input.source !== 'worker') {
            return { status: 400, error: 'source is required (engine or worker)' };
        }
        const result = await controlplane.getStreamMessages(input.namespace, {
            source: input.source,
            limit: input.limit,
            offset: input.offset,
            sort_by: input.sort_by,
            order: input.order,
            status: input.status,
            stream_name: input.stream_name,
            msg_type: input.msg_type,
            topic: input.topic,
            workflow_name: input.workflow_name,
            jid: input.jid,
            aid: input.aid,
        });
        return { status: 200, data: result };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
