/**
 * CommonJS wrapper for ES Module server
 * This file is used by cPanel's Node.js launcher which uses require()
 */

// Set up error handlers FIRST before importing anything
process.on("uncaughtException", (error) => {
  try {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const errorStack = error instanceof Error ? error.stack : undefined;

    console.error(`Uncaught Exception: ${errorMessage}`);
    if (errorStack) {
      console.error(`Stack trace: ${errorStack}`);
    }
    process.exit(1);
  } catch (handlerError) {
    console.error("Fatal error in error handler");
    process.exit(1);
  }
});

process.on("unhandledRejection", (reason, promise) => {
  try {
    let errorMessage = "Unhandled Promise Rejection";
    let errorStack = undefined;

    if (reason instanceof Error) {
      errorMessage = reason.message;
      errorStack = reason.stack;
    } else if (typeof reason === "object" && reason !== null) {
      try {
        errorMessage = JSON.stringify(reason);
      } catch (e) {
        errorMessage = String(reason);
      }
    } else {
      errorMessage = String(reason);
    }

    console.error(`Unhandled Rejection: ${errorMessage}`);
    if (errorStack) {
      console.error(`Stack trace: ${errorStack}`);
    }
  } catch (handlerError) {
    // Ignore errors in handler
  }
});

// Dynamically import the ES module server
(async () => {
  try {
    // Import the ES module server
    const serverModule = await import("./src/server.js");

    // The server.js file exports the Express app as default
    // The server startup is handled inside server.js
    // We just need to ensure the module is loaded

    // If server.js doesn't start automatically, we can check
    // But typically it should start on import

    console.log("Server module loaded successfully");
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const errorStack = error instanceof Error ? error.stack : undefined;

    console.error(`Failed to load server module: ${errorMessage}`);
    if (errorStack) {
      console.error(`Stack trace: ${errorStack}`);
    }
    process.exit(1);
  }
})();

// Export a dummy object so require() doesn't fail
// The actual server is started by the async import above
module.exports = {};
