import uuid from datetime import datetime from typing import Optional, List, Tuple from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from src.models.messages import Message from src.api.repositories.core import DatabaseManager class MessageRepo(DatabaseManager): def __init__(self, session: AsyncSession): super().__init__(session, Message) async def create(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Message: return await super().create(chat_id=chat_id, sender_id=sender_id, text=text) async def get_chat_messages(self, chat_id: uuid.UUID, limit: int = 50, cursor_created_at: Optional[datetime] = None, cursor_msg_id: Optional[uuid.UUID] = None) -> Tuple[List[Message], bool]: query = (select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at.asc(), Message.id.asc()) ) if cursor_created_at is not None and cursor_msg_id is not None: query = query.where((Message.created_at > cursor_created_at) | ((Message.created_at == cursor_created_at) & (Message.id > cursor_msg_id)) ) query = query.limit(limit + 1) result = await self.session.execute(query) messages = list(result.scalars().all()) has_more = len(messages) > limit if has_more: messages = messages[:limit] return messages, has_more