const dotenv = require("dotenv");
// Load env vars first!
dotenv.config({ path: "./config.env" });

const mongoose = require("mongoose");
const app = require("./app");

// 1. Construct the DB URI correctly using the variables in your .env
const DB = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}?authSource=${process.env.DB_AUTH_SOURCE}&directConnection=true&ssl=false`;

// 2. Database connection
mongoose
  .connect(DB) // Modern Mongoose (6+) doesn't need useNewUrlParser/useUnifiedTopology
  .then((conn) => {
    console.log("✅ DB connection successful:", conn.connection.host);
  })
  .catch((err) => {
    console.error("❌ DB connection error:", err.message);
    process.exit(1); // Stop the server if DB fails
  });

// 3. Start server
const port = process.env.PORT || 3000;
const server = app.listen(port, "0.0.0.0", () => {
  console.log(
    `🚀 App running on port ${port} in ${process.env.NODE_ENV} mode...`
  );
});

// 4. Handle Unhandled Rejections (Safety Net)
process.on("unhandledRejection", (err) => {
  console.log("UNHANDLED REJECTION! 💥 Shutting down...");
  console.log(err.name, err.message);
  server.close(() => {
    process.exit(1);
  });
});
