"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = require("http");
const url_1 = require("url");
const next_1 = __importDefault(require("next"));
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const socket_instance_1 = require("./server/socket-instance");
const dotenv_1 = __importDefault(require("dotenv"));
// Import API routes
const auth_1 = __importDefault(require("./server/routes/auth"));
const leads_1 = __importDefault(require("./server/routes/leads"));
const notifications_1 = __importDefault(require("./server/routes/notifications"));
const activities_1 = __importDefault(require("./server/routes/activities"));
const tasks_1 = __importDefault(require("./server/routes/tasks"));
const users_1 = __importDefault(require("./server/routes/users"));
const database_1 = __importDefault(require("./server/routes/database"));
dotenv_1.default.config();
const dev = process.env.NODE_ENV !== "production";
// cPanel/Passenger often uses a named pipe for PORT, so do NOT parse options.PORT to int strictly
const portIsNamedPipe = isNaN(Number(process.env.PORT));
const port = process.env.PORT || 3000;
const hostname = "localhost";
// Logging helper
const fs_1 = __importDefault(require("fs"));
const logFile = './server-startup.log';
const log = (msg) => {
    try {
        const entry = `${new Date().toISOString()} - ${msg}\n`;
        // Ensure file exists or is writable, ignore error if fails (readonly fs)
        fs_1.default.appendFileSync(logFile, entry);
    }
    catch (e) {
        // Fallback to console only if file write fails
    }
    console.log(msg);
};
log(`Starting server... Node Version: ${process.version}`);
log(`Current Working Directory: ${process.cwd()}`);
log(`Environment: ${process.env.NODE_ENV}`);
log(`Port: ${port} (Named Pipe: ${portIsNamedPipe})`);
log("Server Entry v3 Loaded - Fix Use Middleware");
// Initialize Next.js
// Note: When using a custom server with 'next', we must match the build configuration
const app = (0, next_1.default)({ dev, hostname, port: portIsNamedPipe ? 3000 : Number(port) });
// ^ Next.js internal server needs a valid TCP port number for internal bindings even if we listen on a pipe externaly? 
// Actually for 'next({ ... })', the port argument doesn't dictate where Express listens, 
// but it might be used for generating URLs. Safe to pass 3000 if pipe.
const handle = app.getRequestHandler();
app.prepare().then(() => {
    log("Next.js app prepared");
    const server = (0, express_1.default)();
    const httpServer = (0, http_1.createServer)(server);
    // Middleware
    server.use((0, cors_1.default)());
    server.use(express_1.default.json());
    // Logging Middleware
    server.use((req, res, next) => {
        // Skip logging for internal Next.js requests to reduce noise
        if (!req.url.startsWith('/_next') && !req.url.startsWith('/__next')) {
            console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
        }
        next();
    });
    // Setup Socket.io
    (0, socket_instance_1.initSocket)(httpServer);
    // API Routes
    server.use("/api/auth", auth_1.default);
    server.use("/api/leads", leads_1.default);
    server.use("/api/notifications", notifications_1.default);
    server.use("/api/activities", activities_1.default);
    server.use("/api/tasks", tasks_1.default);
    server.use("/api/users", users_1.default);
    server.use("/api/database", database_1.default);
    // Default catch-all handler to allow Next.js to handle all other routes
    // Use regex to avoid "Missing parameter name" error in some Express/env versions
    // Default catch-all handler to allow Next.js to handle all other routes
    // Using server.use() without a path to act as a generic middleware for all unmatched routes
    // This bypasses path-to-regexp parsing strictness for wildcards in Express 5
    server.use((req, res) => {
        const parsedUrl = (0, url_1.parse)(req.url, true);
        return handle(req, res, parsedUrl);
    });
    try {
        httpServer.listen(port, () => {
            log(`> Ready on http://${hostname}:${port}`);
            log(`> Mode: Single-port (API + Next.js)`);
        });
        httpServer.on('error', (err) => {
            log(`SERVER ERROR: ${err.message}`);
            console.error(err);
        });
    }
    catch (err) {
        log(`STARTUP ERROR: ${err}`);
        console.error(err);
    }
}).catch(err => {
    log(`NEXT.JS PREPARE ERROR: ${err}`);
    console.error(err);
});
