from fastapi import HTTPException
from app.core.config import config as Config
from app.core.database import MongoDBClient


def get_ranking_data(limit=10):
    mongodb = MongoDBClient()
    db = mongodb.getDatabase(Config.MONGO_DB)
    collection = mongodb.getCollection(Config.MONGO_REGISTRE_COLLECTION)

    try:
        ranking_data = list(
            collection.find({}, {"messages.user_message": 1, "views": 1, "_id": 0})
            .sort("views", -1)
            .limit(limit)
        )
        formatted_data = []
        for doc in ranking_data:
            messages = [
                f'user_message:{msg.get("user_message", "")}'
                for msg in doc.get("messages", [])
            ]
            formatted_data.append({
                "views": doc.get("views", 0),
                "messages": messages
            })
        return formatted_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error retrieving views ranking: {str(e)}")