""" Database connection for Token Service """ from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase import logging import os logger = logging.getLogger(__name__) # Database configuration MONGO_URL = os.getenv("MONGO_URL", "mongodb://localhost:27017") DATABASE_NAME = os.getenv("DATABASE_NAME", "energy_dashboard_tokens") # Global database client _client: AsyncIOMotorClient = None _database: AsyncIOMotorDatabase = None async def connect_to_mongo(): """Create database connection""" global _client, _database try: _client = AsyncIOMotorClient(MONGO_URL) _database = _client[DATABASE_NAME] # Test connection await _database.command("ping") logger.info(f"Connected to MongoDB: {DATABASE_NAME}") # Create indexes for performance await create_indexes() except Exception as e: logger.error(f"Failed to connect to MongoDB: {e}") raise async def close_mongo_connection(): """Close database connection""" global _client if _client: _client.close() logger.info("Disconnected from MongoDB") async def get_database() -> AsyncIOMotorDatabase: """Get database instance""" global _database if _database is None: raise RuntimeError("Database not initialized. Call connect_to_mongo() first.") return _database async def create_indexes(): """Create database indexes for performance""" db = await get_database() # Indexes for tokens collection await db.tokens.create_index("token", unique=True) await db.tokens.create_index("active") await db.tokens.create_index("expires_at") await db.tokens.create_index("name") logger.info("Database indexes created")