// Required for Node.js 18 on cPanel shared hosting (WebAssembly disabled)
const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 3000;
const path = require("path");
const reportsRoutes = require("./routes/reports");
const usersRoutes = require("./routes/users");
const projectsRoutes = require("./routes/projects");
const SDSRoutes = require("./routes/sds");
const sequelize = require("./db");
const safetyToolsRoutes = require("./routes/safety-tools");
const entranceLogRoutes = require("./routes/entrance-log");
const subscriptionsRoutes = require("./routes/subscriptions");
const companiesRoutes = require("./routes/companies");
const dashboardRoutes = require("./routes/dashboard");
const notificationsRoutes = require("./routes/notifications");
const riskAssessmentRoutes = require("./routes/risk-assessment");
const jobSafetyAnalysisRoutes = require("./routes/job-safety-analysis");
const minutesOfMeetingRoutes = require("./routes/minutes-of-meeting");
const permitToWorkRoutes = require("./routes/permit-to-work");
const hazopRoutes = require("./routes/hazop");
const trainingRoutes = require("./routes/training");
const trainingCoursesRoutes = require("./routes/training-courses");
const leaveRequestsRoutes = require("./routes/leave-requests");
const microsoftAuthRoutes = require("./routes/microsoft-auth");
const superAdminRoutes = require("./routes/superAdmin");
const aiRoutes = require("./routes/ai");
const fileUpload = require("express-fileupload");
const resetUsageMiddleware = require("./middleware/resetUsageMiddleware");

app.use(
  fileUpload({
    createParentPath: true,
    limits: { fileSize: 150 * 1024 * 1024 },
    abortOnLimit: true,
  }),
);

app.use(resetUsageMiddleware);
app.use(
  cors({
    origin: [
      "https://app.nordsafe-ehs.com",
      "https://test.nordsafe-ehs.com",
      "http://localhost:5173",
    ],
    credentials: true,
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization"]
  }),
);
app.use((req, res, next) => {
  if (req.originalUrl === "/api/subscriptions/webhook")
    express.raw({ type: "application/json" })(req, res, next);
  else if (req.is("application/json")) express.json()(req, res, next);
  else next();
});
app.use("/sds-files", express.static(path.join(__dirname, "sds-files")));
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.use(
  "/training-videos",
  express.static(path.join(__dirname, "training-videos")),
);

sequelize
  .sync()
  .then(async () => {
    console.log("Database synced successfully.");
  })
  .catch((err) => {
    console.error("Database sync failed:", err);
  });

app.use("/api/reports", reportsRoutes);
app.use("/api/users", usersRoutes);
app.use("/api/projects", projectsRoutes);
app.use("/api/sds", SDSRoutes);
app.use("/api/safety-tools", safetyToolsRoutes);
app.use("/api/entrance-log", entranceLogRoutes);
app.use("/api/subscriptions", subscriptionsRoutes);
app.use("/api/companies", companiesRoutes);
app.use("/api/dashboard", dashboardRoutes);
app.use("/api/notifications", notificationsRoutes);
app.use("/api/risk-assessment", riskAssessmentRoutes);
app.use("/api/job-safety-analysis", jobSafetyAnalysisRoutes);
app.use("/api/minutes-of-meeting", minutesOfMeetingRoutes);
app.use("/api/permit-to-work", permitToWorkRoutes);
app.use("/api/hazop", hazopRoutes);
app.use("/api/training", trainingRoutes);
app.use("/api/training-courses", trainingCoursesRoutes);
app.use("/api/leave-requests", leaveRequestsRoutes);
app.use("/api/auth/microsoft", microsoftAuthRoutes);
app.use("/api/super-admin", superAdminRoutes);
app.use("/api/ai", aiRoutes);

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