"""MongoDB database connection and utilities""" from motor.motor_asyncio import AsyncIOMotorClient from typing import Optional from app.config import settings import logging logger = logging.getLogger(__name__) class Database: client: Optional[AsyncIOMotorClient] = None database = None db = Database() async def connect_database(): """Create database connection""" try: db.client = AsyncIOMotorClient(settings.mongodb_url) db.database = db.client[settings.database_name] # Test connection await db.client.server_info() logger.info("Successfully connected to MongoDB") # Create indexes await create_indexes() except Exception as e: logger.error(f"Failed to connect to MongoDB: {e}") raise async def disconnect_database(): """Close database connection""" if db.client: db.client.close() logger.info("Disconnected from MongoDB") async def create_indexes(): """Create database indexes for better performance""" try: # Users collection indexes users_collection = db.database["users"] await users_collection.create_index("email", unique=True) await users_collection.create_index("username", unique=True) await users_collection.create_index("created_at") # Applications collection indexes apps_collection = db.database["applications"] await apps_collection.create_index("client_id", unique=True) await apps_collection.create_index("created_by") await apps_collection.create_index("created_at") # Auth history collection indexes history_collection = db.database["auth_history"] await history_collection.create_index("user_id") await history_collection.create_index("application_id") await history_collection.create_index("created_at") await history_collection.create_index( [("created_at", 1)], expireAfterSeconds=2592000 # 30 days ) # Refresh tokens collection indexes tokens_collection = db.database["refresh_tokens"] await tokens_collection.create_index("token", unique=True) await tokens_collection.create_index("user_id") await tokens_collection.create_index("expires_at") await tokens_collection.create_index( [("expires_at", 1)], expireAfterSeconds=0 ) logger.info("Database indexes created successfully") except Exception as e: logger.error(f"Failed to create indexes: {e}") def get_database(): """Get database instance""" return db.database