const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const https = require("https");
const fs = require("fs");

const leadsRoutes = require("./routes/leadsRoutes");
const dataRoutes = require("./routes/dataRoutes");
const questionRoutes = require("./routes/questionRoutes");
const woocommerceRoutes = require("./routes/woocommerceRoutes");
const app = express();

// CORS configuration
app.use(
  cors({
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true,
  })
);

// Define a custom token for request duration
morgan.token("duration", (req, res) => {
  const start = process.hrtime();
  res.on("finish", () => {
    const durationInMilliseconds =
      process.hrtime(start)[0] * 1000 + process.hrtime(start)[1] / 1000000;
    console.log(`Request took ${durationInMilliseconds.toFixed(3)} ms`);
  });
  return "";
});

// Morgan middleware for logging requests with duration
app.use(
  morgan(
    ":method :url :status :res[content-length] - :response-time ms - :duration"
  )
);

// Body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use("/api/data", dataRoutes);
app.use("/api/leads", leadsRoutes);
app.use("/api/questions", questionRoutes);
app.use("/api/woocommerce", woocommerceRoutes);

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send("Something broke!");
});

const privateKey = fs.readFileSync("../../../../ssl/keys/b92f2_a4259_bfad38b871ce0d413aaa5989093f567b.key", "utf8");
const certificate = fs.readFileSync("../../../../ssl/certs/api_pcc_co_il_b92f2_a4259_1713357559_510db2bafa94588f233a03b8310610b3.crt", "utf8");

const credentials = { key: privateKey, cert: certificate };

const PORT = process.env.PORT || 3000;

https.createServer(credentials, app).listen(PORT, () => {
  console.log("HTTPS server running on port 3000");
});
