const express = require("express");
const bodyParser = require("body-parser");
// const rateLimit = require("express-rate-limit");
const path = require("path");
const multerConfig = require("./util/multer");

const mainRoutes = require("./routes/main-route");
const mainRoutesv2 = require("./routes/main-route-v2");
const mainRoutesv3 = require("./routes/main-route-v3");
const cors = require("./util/cors");
const sequelizeConnect = require("./connection/db");
const passport = require("./util/passport-config");
const logger = require("./util/logger");

const publicPath = path.join(__dirname, "public");
const app = express();

// Service PDC Payments
// require("./services/buildcredit-payments-pdc");

// Service BuildCredit Due Date
// require("./services/buildcredit-due-date");

// Service BuildCredit Monthly Balance
// require("./services/buildcredit-monthly-balance-text");

// Service Inactive Customers
// require("./services/inactive-customers-text");

app.use("/public/", express.static(publicPath));

// const apiLimiter = rateLimit({
//   windowMs: 15 * 60 * 1000, // 15 minutes
//   max: 50,
//   message: "Too many requests from this IP, please try again later.",
// });

app.use(bodyParser.json());
app.use(passport.initialize());
app.use(multerConfig);
// app.use("/api/v1", cors, apiLimiter, mainRoutes);
app.use("/api/v1", cors, mainRoutes);
app.use("/api/v1.1", cors, mainRoutesv2);
app.use("/api/v3", cors, mainRoutesv3);

// Error Handler
app.use((error, req, res, next) => {
  console.log(error);
  const status = error.statusCode || 500;
  const message = error.message;
  const data = error.data;
  logger.error(`Status: ${status}, Message: ${message}, Data: ${JSON.stringify(data)}, Stack: ${error.stack}`);
  res.status(status).json({ success: false, message: message, data: data });
});

// Server
const port = process.env.port || 3000;

sequelizeConnect
  .sync({
    // force: true,
  })
  .then((res) => {
    app.listen(port, () => {
      console.log("Server Started at PORT: ", port);
    });
  })
  .catch((err) => {
    console.error(err);
  });
