import { Router } from '../../../../src/index.js';
import { createSnapshotBuilder } from './api/TelemetryAPI.js';
import { teleStream } from './api/TelemetryMonitoringService.js';
import { getDashboardHtml } from './routes/dashboard.js';
const DEFAULTS = {
    enabled: true,
    basePath: '/telemetry',
    autoRefresh: true,
    refreshIntervalMs: 10000,
};
export const TelemetryDashboard = Object.freeze({
    create(config) {
        const settings = buildSettings(config);
        const buildSnapshot = createSnapshotBuilder();
        const registerRoutes = createRouteRegistrar(settings, buildSnapshot);
        return Object.freeze({ registerRoutes });
    },
});
function buildSettings(config) {
    return {
        enabled: config.enabled ?? DEFAULTS.enabled,
        basePath: config.basePath ?? DEFAULTS.basePath,
        middleware: config.middleware ?? [],
        autoRefresh: config.autoRefresh ?? DEFAULTS.autoRefresh,
        refreshIntervalMs: typeof config.refreshIntervalMs === 'number' && Number.isFinite(config.refreshIntervalMs)
            ? Math.max(1000, Math.floor(config.refreshIntervalMs))
            : DEFAULTS.refreshIntervalMs,
    };
}
function createRouteRegistrar(settings, buildSnapshot) {
    return (router) => {
        if (!settings.enabled)
            return;
        const routeOptions = (settings.middleware.length > 0 ? { middleware: settings.middleware } : undefined);
        registerDashboardRoute(router, settings, routeOptions);
        registerSummaryApi(router, settings, routeOptions, buildSnapshot);
        registerEventsApi(router, settings, routeOptions, buildSnapshot);
    };
}
function registerDashboardRoute(router, settings, routeOptions) {
    Router.get(router, settings.basePath, (_req, res) => {
        res.html(getDashboardHtml({
            basePath: settings.basePath,
            autoRefresh: settings.autoRefresh,
            refreshIntervalMs: settings.refreshIntervalMs,
        }));
    }, routeOptions);
}
function registerSummaryApi(router, settings, routeOptions, buildSnapshot) {
    Router.get(router, `${settings.basePath}/api/summary`, async (_req, res) => {
        const snapshot = await buildSnapshot();
        res.json(snapshot);
    }, routeOptions);
}
function registerEventsApi(router, settings, routeOptions, buildSnapshot) {
    Router.get(router, `${settings.basePath}/api/events`, async (_req, res) => {
        teleStream(res, settings, buildSnapshot);
    }, routeOptions);
}
export default TelemetryDashboard;
