"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.startProjectServer = startProjectServer;
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const configRepository_js_1 = require("../repositories/configRepository.js");
// Import routers
const projectRoutes_js_1 = require("./routes/projectRoutes.js");
const logRoutes_js_1 = require("./routes/logRoutes.js");
const configRoutes_js_1 = require("./routes/configRoutes.js");
const serverRoutes_js_1 = require("./routes/serverRoutes.js");
const traceRoutes_js_1 = require("./routes/traceRoutes.js");
async function startProjectServer(logger) {
    try {
        // Use custom logger if provided, otherwise use console
        const log = logger?.log || console.log;
        const error = logger?.error || console.error;
        // Set up global error handlers to prevent server crashes
        process.on('uncaughtException', (err) => {
            error('Uncaught Exception:', err);
            // Don't exit the process, just log the error
        });
        process.on('unhandledRejection', (reason, promise) => {
            error('Unhandled Rejection at:', promise, 'reason:', reason);
            // Don't exit the process, just log the error
        });
        // Create Express app
        const app = (0, express_1.default)();
        // Use ConfigRepository for config access
        const configRepo = new configRepository_js_1.ConfigRepository();
        // Check if server is enabled - default to true if not set
        const enabledConfig = await configRepo.getValue('server.enabled');
        const isEnabled = enabledConfig !== 'false'; // Default to true if not set
        if (!isEnabled) {
            log('Project API server is disabled in settings');
            return null;
        }
        // Get CORS configuration
        const corsConfig = await configRepo.getValue('server.corsOrigins');
        let corsOrigins = ['http://localhost:5173', 'http://localhost:3001', 'http://localhost:8081', 'http://localhost:2345']; // Default
        if (corsConfig) {
            try {
                const parsedOrigins = JSON.parse(corsConfig);
                if (Array.isArray(parsedOrigins) && parsedOrigins.length > 0) {
                    // Merge default origins with database origins, removing duplicates
                    corsOrigins = [...new Set([...corsOrigins, ...parsedOrigins])];
                }
            }
            catch (err) {
                error('Error parsing CORS origins:', err);
            }
        }
        console.log("sitting up with origins: ", corsOrigins);
        // Middleware
        app.use(express_1.default.json());
        app.use((0, cors_1.default)({
            origin: corsOrigins,
            methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
            allowedHeaders: ['Content-Type', 'Authorization'],
            credentials: true,
        }));
        // Mount routers with top-level try-catch for each route
        try {
            app.use('/api/projects', (0, projectRoutes_js_1.createProjectRouter)());
            app.use('/api/logs', (0, logRoutes_js_1.createLogRouter)());
            app.use('/api/config', (0, configRoutes_js_1.createConfigRouter)());
            app.use('/api/server', (0, serverRoutes_js_1.createServerRouter)());
            app.use('/api/traces', (0, traceRoutes_js_1.createTraceRouter)());
            app.use('/api', (0, projectRoutes_js_1.createProjectRouter)()); // Mount again for metadata routes
        }
        catch (routeError) {
            error('Error mounting routes:', routeError);
            throw routeError;
        }
        // Error handling middleware
        app.use((err, req, res, next) => {
            try {
                log(`Server Error: ${req.method} ${req.url} - ${err.message}`, err.stack);
                // For more detailed error logging, you can log the full error object:
                // log('Full Server Error Object:', err);
                if (!res.headersSent) {
                    res.status(500).json({ error: 'Internal server error', message: err.message });
                }
                else {
                    // If headers already sent, delegate to the default Express error handler
                    next(err);
                }
            }
            catch (middlewareError) {
                error('Error in error handling middleware:', middlewareError);
                // Fallback error response
                if (!res.headersSent) {
                    res.status(500).json({ error: 'Critical server error' });
                }
            }
        });
        // Get port from config or use default
        const port = await configRepo.getValue('server.port') || 3001;
        log(`Starting server on port ${port}`);
        const server = app.listen(Number(port), () => {
            log(`Server running on http://localhost:${port}`);
        });
        // Handle server errors
        server.on('error', (serverError) => {
            error('Server error:', serverError);
        });
        return server;
    }
    catch (err) {
        const errorLogger = logger?.error || console.error;
        errorLogger('Failed to start server:', err);
        throw err;
    }
}
//# sourceMappingURL=server.js.map