import "dotenv/config";
import mongoose from "mongoose";

const testConnection = async () => {
  const uri = process.env.MONGODB_URI || "mongodb://localhost:27017/samaa";
  
  console.log("Testing MongoDB connection...");
  console.log("URI:", uri.replace(/\/\/([^:]+):([^@]+)@/, "//***:***@"));
  
  try {
    await mongoose.connect(uri, {
      serverSelectionTimeoutMS: 5000,
    });
    
    console.log("✅ MongoDB connection successful!");
    console.log("Host:", mongoose.connection.host);
    console.log("Port:", mongoose.connection.port);
    console.log("Database:", mongoose.connection.name);
    console.log("Ready State:", mongoose.connection.readyState);
    
    await mongoose.connection.close();
    process.exit(0);
  } catch (error) {
    console.error("❌ MongoDB connection failed!");
    console.error("Error:", error.message);
    
    if (error.name === "MongoServerSelectionError") {
      console.error("\nPossible issues:");
      console.error("1. MongoDB is not running");
      console.error("2. Wrong connection string");
      console.error("3. Network/firewall blocking connection");
      console.error("4. MongoDB not installed");
    }
    
    process.exit(1);
  }
};

testConnection();

