const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");

// Tối ưu hóa memory
process.env.NODE_ENV = "production";

const app = next({ dev: false });
const handle = app.getRequestHandler();

const port = parseInt(process.env.PORT || "3000", 10);

app
  .prepare()
  .then(() => {
    createServer((req, res) => {
      // Thêm cache headers
      res.setHeader("Cache-Control", "public, max-age=3600");

      const parsedUrl = parse(req.url, true);
      handle(req, res, parsedUrl);
    }).listen(port, (err) => {
      if (err) throw err;
      console.log(`> Ready on http://localhost:${port}`);
    });
  })
  .catch((err) => {
    console.error("Failed to start server:", err);
    process.exit(1);
  });
