from pymongo.collection import Collection
from pymongo.database import Database
from typing import Optional
from app.models.entities import SessionEntity


class SessionRepository:
    COLLECTION_NAME = "session"

    def __init__(self, db: Database):
        self.collection: Collection = db[self.COLLECTION_NAME]
        # self.collection.create_index("id", unique=True)

    def insert(self, session_data: SessionEntity) -> str:
        print(session_data.model_dump(by_alias=True, exclude_none=True))
        result = self.collection.insert_one(
            session_data.model_dump(by_alias=True, exclude_none=True)
        )
        return str(result.inserted_id)

    def find_by_session_id(self, session_id: str) -> Optional[SessionEntity]:
        doc = self.collection.find_one({"_id": session_id})
        return SessionEntity(**doc) if doc else None

    def find_by_session_code(self, session_code: str) -> Optional[SessionEntity]:
        doc = self.collection.find_one({"session_code": session_code})
        return SessionEntity(**doc) if doc else None

    def update(self, session_id: str, update_fields: SessionEntity) -> bool:
        """Update specific fields using $set"""
        result = self.collection.update_one(
            {"_id": session_id},
            {"$set": update_fields},
        )
        return result.modified_count > 0

    def add_participant(self, session_id: str, user_id: str) -> bool:
        """Add user_id to participants array without duplicates"""
        result = self.collection.update_one(
            {"_id": session_id}, {"$addToSet": {"participants": user_id}}
        )
        return result.modified_count > 0

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

    def list_active_sessions(self) -> list[SessionEntity]:
        docs = self.collection.find({"is_active": True})
        return [SessionEntity(**doc) for doc in docs]
