import motor.motor_asyncio
from bson import ObjectId
from typing import Optional
from fastapi import HTTPException
from ..constant import MONGODB_URL,DATABASE_NAME

# Initialize the MongoDB client
client = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URL)
db = client[DATABASE_NAME]  # Connect to the database

# MongoDB ObjectId Pydantic model for FastAPI response
class ObjectIdStr(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, value):
        if isinstance(value, ObjectId):
            return str(value)
        if isinstance(value, str) and ObjectId.is_valid(value):
            return value
        raise ValueError("Invalid ObjectId")


# You can define the MongoDB collections here
boxpc_specs_collection = db["boxpc_specs"] 
motherboard_specs_collection = db["motherboard_specs"] 
filters_collection = db["filters"] 
rpa_logs_collection = db["RPA_logs"]
facet_collection = db["facets"]
users_collection = db["users"]
roles_collection = db["roles"]
product_url = db["product_url"]


# Function to check if the database is accessible
async def test_connection():
    try:
        # Perform a simple database operation to check the connection
        await client.admin.command('ping')  # This sends a ping command to MongoDB to check the connection
        return True
    except Exception as e:
        raise HTTPException(status_code=500, detail="Database connection failed")

# Close the MongoDB client when the app shuts down
def close_client():
    client.close()
