const { createServer } = require("node:http");

const application = import("./dist/application.js");
const server = createServer((request, response) => {
  void application
    .then(({ handleBridgeRequest }) => handleBridgeRequest(request, response))
    .catch((error) => {
      response.writeHead(503, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
      response.end(JSON.stringify({ code: "BRIDGE_STARTING", message: error instanceof Error ? error.message : "Bridge is starting" }));
    });
});

const port = Number(process.env.PORT || 8789);
const host = process.env.HOST || "127.0.0.1";
server.listen(port, host);

function shutdown() {
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
