import express from "express";
import cors from "cors";
import apiRouter from "./routes/api.js";

const app = express();
const port = 7001;
import { rateLimit } from "express-rate-limit";

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.json());

const limits = {
  time: 1, // = 1 minute
  requests: 10, // = maximum 10 requests
};

const limiter = rateLimit({
  windowMs: limits.time * 60 * 1000,
  limit: limits.requests,
  standardHeaders: "draft-8", // draft-6: `RateLimit-*` headers; draft-7 & draft-8: combined `RateLimit` header
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
  ipv6Subnet: 56, // Set to 60 or 64 to be less aggressive, or 52 or 48 to be more aggressive
});

app.use(limiter);

app.get("/", (req, res) => {
  res.render("index.ejs", { title: port });
});

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

// error handling code
app.use((err, req, res, next) => {
  // Log the error stack and send a generic error response
  console.error(err.stack);
  res.status(500).send("Something broke!");
});
