const express = require("express");
const cors = require("cors");
const fs = require("fs");
const path = require("path");
const https = require("https");
const dotenv = require("dotenv");
const dataRoutes = require("./routes/dataRoutes");

dotenv.config(); // Load environment variables

const app = express();
const PORT = process.env.DB_PORT || 5000;

// Middleware to parse JSON requests
app.use(express.json());

// Improved CORS configuration
const corsOptions = {
  origin: "*", // Consider restricting this in production
  methods: "GET,POST,PUT,DELETE",
  allowedHeaders: "Content-Type,Authorization",
};
app.use(cors(corsOptions));

// Read SSL certificate files with error handling
let options = {};
try {
  options = {
    cert: fs.readFileSync(path.resolve(__dirname, "dialer.crt")),
    key: fs.readFileSync(path.resolve(__dirname, "dialer.key")),
    ca: fs.readFileSync(path.resolve(__dirname, "ca-bundle.pem"))
  };
//   console.log(options);
} catch (error) {
  console.error("SSL certificate files missing or invalid:", error.message);
  process.exit(1); // Exit the process if SSL files are not found
}

// Define API routes
app.use("/api/acefone", dataRoutes);

// Basic route for testing
app.get("/", (req, res) => {
  res.send("Hello, Secure World!");
});

// Create HTTPS server with proper error handling
const server = https.createServer(options, app);
console.log(server);

server.listen(PORT, () => {
  console.log(`Secure server is running on ${PORT}`);
});

// Handle errors globally
server.on("error", (err) => {
  console.error("Server error:", err);
});
