var express = require("express");
var cors = require("cors");
var mongoose = require("mongoose");
var dotenv = require("dotenv");
var session = require("express-session");
var connectDB = require("./config/db");

var userRoutes = require("./routes/userRoutes");
var supplierRoutes = require("./routes/supplierRoutes");
var shipmentRoutes = require("./routes/shipmentRoutes");
var deliveryRoutes = require("./routes/deliveryRoutes");

dotenv.config();

var app = express();
var PORT = process.env.PORT || 5000;
var defaultOrigins = ["http://localhost:5173", "http://localhost:5174"];
var clientOrigins = (process.env.CLIENT_URLS || "") + "," + (process.env.CLIENT_URL || "");
var envOrigins = clientOrigins
  .split(",")
  .map(function (origin) {
    return origin.trim();
  })
  .filter(Boolean);
var allowedOrigins = defaultOrigins.concat(envOrigins).filter(function (origin, index, origins) {
  return origins.indexOf(origin) === index;
});

connectDB();

app.use(
  cors({
    origin: function (origin, callback) {
      if (!origin || allowedOrigins.indexOf(origin) !== -1) {
        return callback(null, true);
      }

      return callback(new Error("Not allowed by CORS"));
    },
    credentials: true,
  })
);
app.use(express.json());
app.use(
  session({
    secret: process.env.SESSION_SECRET || "scms_exam_secret",
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: false,
      sameSite: "lax",
      maxAge: 1000 * 60 * 60,
    },
  })
);

app.get("/", function (req, res) {
  res.send("Supply Chain Management System API is running");
});

app.use("/api/users", userRoutes);
app.use("/api/suppliers", supplierRoutes);
app.use("/api/shipments", shipmentRoutes);
app.use("/api/deliveries", deliveryRoutes);

app.listen(PORT, function () {
  console.log("SCMS server is running on port " + PORT);
  console.log("Mongoose connection state: " + mongoose.connection.readyState);
});
