/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require("fs");
const path = require("path");

const port = process.env.PORT || 3001;

const standaloneEntry = path.join(
  __dirname,
  ".next",
  "standalone",
  "server.js"
);

if (fs.existsSync(standaloneEntry)) {
  // Preferred: run the standalone server generated by `next build`.
  require(standaloneEntry);
} else {
//   const buildIdPath = path.join(__dirname, ".next", "BUILD_ID");
//   if (!fs.existsSync(buildIdPath)) {
//     console.error(
//       "Missing production build. Run `npm run build` and upload the `.next` folder."
//     );
//     process.exit(1);
//   }

  const next = require("next");
  const http = require("http");

  const dev = false;
  const app = next({ dev, dir: path.resolve(__dirname) });
  const handle = app.getRequestHandler();

  app
    .prepare()
    .then(() => {
      http
        .createServer((req, res) => {
          handle(req, res);
        })
        .listen(port, () => {
          console.log("Next.js running on port", port);
        });
    })
    .catch((err) => {
      console.error("Error starting server:", err);
      process.exit(1);
    });
}
