import mongoose from "mongoose";

// MongoDB connection URL. This should be configured in your environment variables.
const MONGO_URL = process.env.MONGO_URI || "mongodb://oms:oms123.@localhost:27717/omsdb?authSource=admin";

/**
 * Connects to the MongoDB database.
 * This function should be called once at the application's startup.
 * @returns {Promise<void>}
 */
export const connectToDatabase = async (): Promise<void> => {
  try {
    if (mongoose.connection.readyState === 1) {
      console.log("[Database] Already connected to MongoDB.");
      return;
    }
    await mongoose.connect(MONGO_URL);
    console.log("[Database] Successfully connected to MongoDB.");
  } catch (error) {
    console.error("[Database] Failed to connect to MongoDB:", error);
    process.exit(1); // Exit process if connection fails
  }
};

/**
 * Disconnects from the MongoDB database.
 * This function should be called on application shutdown.
 * @returns {Promise<void>}
 */
export const disconnectFromDatabase = async (): Promise<void> => {
  try {
    await mongoose.disconnect();
    console.log("[Database] Disconnected from MongoDB.");
  } catch (error) {
    console.error("[Database] Error disconnecting from MongoDB:", error);
  }
};
