"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LTExpressAdapter = void 0;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const express_1 = __importStar(require("express"));
const routes_1 = __importDefault(require("../routes"));
const events_1 = require("../lib/events");
const socketio_1 = require("../lib/events/socketio");
/**
 * Express adapter for mounting the Long Tail dashboard at an arbitrary subpath
 * inside an existing Express-based application (NestJS, Fastify-Express, etc.).
 *
 * @example NestJS
 * ```typescript
 * import { LTExpressAdapter } from '@hotmeshio/long-tail';
 *
 * const adapter = new LTExpressAdapter();
 * adapter.setBasePath('/admin/longtail');
 *
 * @Module({})
 * export class LongTailUiModule implements NestModule {
 *   configure(consumer: MiddlewareConsumer) {
 *     consumer
 *       .apply(adapter.getRouter())
 *       .forRoutes('/admin/longtail');
 *   }
 *
 *   async onModuleInit() {
 *     // Attach socket.io to the host's HTTP server for real-time events
 *     const httpServer = this.httpAdapterHost.httpAdapter.getHttpServer();
 *     await adapter.attachServer(httpServer);
 *   }
 * }
 * ```
 *
 * @example Express
 * ```typescript
 * import { LTExpressAdapter } from '@hotmeshio/long-tail';
 *
 * const adapter = new LTExpressAdapter();
 * adapter.setBasePath('/admin/longtail');
 * app.use('/admin/longtail', adapter.getRouter());
 *
 * const server = app.listen(3000);
 * await adapter.attachServer(server);
 * ```
 */
class LTExpressAdapter {
    constructor() {
        this.basePath = '';
    }
    /**
     * Set the subpath where the dashboard is mounted.
     * Omit or pass '' for root-level deployment (standalone mode).
     */
    setBasePath(basePath) {
        this.basePath = basePath.replace(/\/+$/, '');
    }
    /**
     * Attach Socket.IO to the host's HTTP server for real-time events.
     *
     * When Long Tail is started with `server: { enabled: false }` (embedded mode),
     * the internal server is not created. Call this after the host server is
     * listening so Socket.IO can bind to it with the correct subpath.
     *
     * Safe to call even when no Socket.IO adapter is registered — it no-ops.
     */
    async attachServer(server) {
        const socketAdapter = events_1.eventRegistry.getAdapter(socketio_1.SocketIOEventAdapter);
        if (socketAdapter) {
            // Override the socket.io path to include the base path
            if (this.basePath) {
                socketAdapter.setPath(`${this.basePath}/socket.io`);
            }
            socketAdapter.attachServer(server);
            await socketAdapter.connect();
        }
    }
    /**
     * Return a self-contained Express Router that serves:
     * - `/api/*` — Long Tail API routes (auth, tasks, escalations, etc.)
     * - `/health` — health check
     * - Static dashboard assets
     * - SPA fallback with injected `<base href>` and `window.__LT_BASE__`
     */
    getRouter() {
        const router = (0, express_1.Router)();
        router.use(express_1.default.json());
        // Health check
        router.get('/health', (_req, res) => {
            res.json({ status: 'ok', timestamp: new Date().toISOString() });
        });
        // API routes — internal routes handle their own JWT auth
        router.use('/api', routes_1.default);
        // Dashboard static assets
        const dashboardDist = this.resolveDashboardDist();
        if (dashboardDist) {
            router.use(express_1.default.static(dashboardDist, { index: false }));
            // SPA fallback — inject base path into index.html
            const indexHtml = (0, fs_1.readFileSync)(path_1.default.join(dashboardDist, 'index.html'), 'utf-8');
            const basePath = this.basePath;
            // Serve __LT_BASE__ as external script (CSP-safe, no inline scripts)
            router.get('/config.js', (_req, res) => {
                res.type('application/javascript').send(`window.__LT_BASE__="${basePath}";`);
            });
            router.get('/{*splat}', (_req, res) => {
                const html = indexHtml.replace('<head>', '<head>' +
                    `<base href="${basePath}/">` +
                    `<script src="./config.js"></script>`);
                res.type('html').send(html);
            });
        }
        return router;
    }
    resolveDashboardDist() {
        // Check multiple paths relative to the compiled output location:
        // - Dev (ts-node from repo root): adapters/ -> dashboard/dist
        // - Prod (node build/): build/adapters/ -> dashboard/dist
        // - npm package: node_modules/@hotmeshio/long-tail/build/adapters/ -> dashboard/dist
        const candidates = [
            path_1.default.join(__dirname, '..', 'dashboard', 'dist'),
            path_1.default.join(__dirname, '..', '..', 'dashboard', 'dist'),
        ];
        for (const candidate of candidates) {
            if ((0, fs_1.existsSync)(candidate))
                return candidate;
        }
        return null;
    }
}
exports.LTExpressAdapter = LTExpressAdapter;
