"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.startServer = startServer;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const express_1 = __importDefault(require("express"));
const config_1 = require("../modules/config");
const logger_1 = require("../lib/logger");
const routes_1 = __importDefault(require("../routes"));
/**
 * Create and start the embedded Express server with health check,
 * API routes, and optional dashboard static assets.
 */
function startServer() {
    const app = (0, express_1.default)();
    if (process.env.NODE_ENV !== 'production') {
        app.disable('etag');
    }
    app.use(express_1.default.json());
    app.get('/health', (_req, res) => {
        res.json({ status: 'ok', timestamp: new Date().toISOString() });
    });
    app.use('/api', routes_1.default);
    // Serve dashboard static assets
    // Resolves correctly in both dev (ts-node from root) and prod (node build/)
    const devDist = path_1.default.join(__dirname, '..', 'dashboard', 'dist');
    const prodDist = path_1.default.join(__dirname, '..', '..', 'dashboard', 'dist');
    const dashboardDist = (0, fs_1.existsSync)(devDist) ? devDist : prodDist;
    if ((0, fs_1.existsSync)(dashboardDist)) {
        app.use(express_1.default.static(dashboardDist));
        // SPA fallback — inject <base href="/"> so relative asset paths
        // resolve from root regardless of route depth (e.g. /admin/users).
        const rawHtml = (0, fs_1.readFileSync)(path_1.default.join(dashboardDist, 'index.html'), 'utf-8');
        const indexHtml = rawHtml.replace('<head>', '<head><base href="/">');
        app.get('/{*splat}', (_req, res) => {
            res.type('html').send(indexHtml);
        });
        logger_1.loggerRegistry.info(`[long-tail] Dashboard: http://localhost:${config_1.config.PORT}/`);
    }
    const httpServer = app.listen(config_1.config.PORT, () => {
        logger_1.loggerRegistry.info(`[long-tail] server running on port ${config_1.config.PORT}`);
        logger_1.loggerRegistry.info(`[long-tail] API: http://localhost:${config_1.config.PORT}/api`);
        logger_1.loggerRegistry.info(`[long-tail] Health: http://localhost:${config_1.config.PORT}/health`);
    });
    return httpServer;
}
