from pymongo.collection import Collection
from bson import ObjectId
from typing import Optional, List
from app.models import UserAnswerEntity


class UserAnswerRepository:
    def __init__(self, db):
        self.collection: Collection = db.user_answers

    def create(self, answer_session: UserAnswerEntity) -> str:
        data = answer_session.model_dump(by_alias=True, exclude_none=True)
        result = self.collection.insert_one(data)
        return str(result.inserted_id)

    def get_by_id(self, id: str) -> Optional[UserAnswerEntity]:
        result = self.collection.find_one({"_id": ObjectId(id)})
        if not result:
            return None
        return UserAnswerEntity(**result)

    def get_by_user_and_quiz(self, user_id: str, quiz_id: str) -> List[dict]:
        result = self.collection.find(
            {"user_id": user_id, "quiz_id": ObjectId(quiz_id)}
        )
        return list(result)

    def get_by_user(self, user_id: str) -> list[UserAnswerEntity]:
        result = self.collection.find({"user_id": user_id})
        return [UserAnswerEntity(**doc) for doc in result]

    def get_by_session(self, session_id: str) -> List[dict]:
        result = self.collection.find({"session_id": ObjectId(session_id)})
        return list(result)

    def delete_by_id(self, id: str) -> bool:
        result = self.collection.delete_one({"_id": ObjectId(id)})
        return result.deleted_count > 0
