import mongoose from "mongoose";
import logger from "../utils/logger.js";
import config from "../config/index.js";

export async function connectDatabase() {
  const mongoUrl = process.env.MONGO_URL || process.env.MONGODB_URI || config.database.mongoUrl;
  if (!mongoUrl) {
    throw new Error("MONGODB_URI or MONGO_URL is not set. Please configure your MongoDB connection string in .env file.");
  }
  
  // Log connection attempt (mask password for security)
  const maskedUrl = mongoUrl.replace(/(mongodb\+srv?:\/\/[^:]+:)([^@]+)(@.+)/, '$1****$3');
  logger.info(`Attempting to connect to MongoDB: ${maskedUrl}`);
  
  const dbName = process.env.MONGODB_DB_NAME || process.env.MONGO_DB_NAME;
  if (dbName) {
    logger.info(`Using database: ${dbName}`);
  }
  
  mongoose.set("strictQuery", true);
  
  try {
    await mongoose.connect(mongoUrl, {
      dbName: dbName || undefined,
      retryWrites: true,
      w: 'majority',
    });
    logger.info("Connected to MongoDB successfully");
    logger.info(`Database: ${mongoose.connection.db.databaseName}`);
  } catch (error) {
    logger.error("MongoDB connection error:", error.message);
    throw error;
  }
}



