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 mainRoutesv4 = require("./routes/main-route-v4");
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 redisClient = require("./helpers/redis");
const app = express();

// Yield Instance
const getYieldClient = require("./helpers/withyield");

app.use(async (req, res, next) => {
  await redisClient.initialize();
  req.redisClient = redisClient;
  next();
});

app.use(async (req, res, next) => {
  try {
    req.yieldClient = await getYieldClient();
    next();
  } catch (error) {
    console.error("Yield client initialization failed:", error);
    res.status(500).send("Service unavailable");
  }
});

// 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");

// require("./services/trigger-delivered-orders");

require("./services/order-expired-ro");

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);
app.use("/api/v4", cors, mainRoutesv4);

// 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);
  });
