"""MongoDB database connection management."""
from pymongo import MongoClient
from pymongo.database import Database as MongoDatabase

from app.config import Config

class Database:
    """MongoDB connection management class."""
    _client: MongoClient | None = None
    _db: MongoDatabase | None = None

    @classmethod
    def connect(cls) -> None:
        """Initialize MongoDB connection."""
        if cls._client is None:
            cls._client = MongoClient(Config.MONGODB_URI)
            cls._db = cls._client[Config.MONGODB_DB_NAME]

    @classmethod
    def get_db(cls) -> MongoDatabase:
        """Get database instance."""
        if cls._db is None:
            cls.connect()
        if cls._db is None:
            raise RuntimeError("Database not connected")
        return cls._db

    @classmethod
    def disconnect(cls) -> None:
        """Close MongoDB connection."""
        if cls._client is not None:
            cls._client.close()
            cls._client = None
            cls._db = None

def get_db() -> MongoDatabase:
    """Helper function to get database"""
    return Database.get_db()
