from core.errors.errors import not_a_member_of_chat from core.models.message.db import MPChat from core.models.message.responses import ChatResponse, ProfileResponse from core.storage import chat_storage class Service: async def build_chat_response(self, chat: MPChat) -> ChatResponse: return ChatResponse(id=chat.id, name=chat.name, admin=ProfileResponse(id=chat.admin.id, external_id=chat.admin.external_id, created_at=chat.admin.created_at, modified_at=chat.admin.modified_at), users=[ProfileResponse(id=user.id, external_id=user.external_id, created_at=user.created_at, modified_at=user.modified_at) for user in chat.users], created_at=chat.created_at, modified_at=chat.modified_at) async def create_chat(self, name: str, admin_id: int) -> ChatResponse: chat = await chat_storage.create_chat(name=name, admin_id=admin_id) chat = await chat_storage.add_member(chat.id, admin_id) return await self.build_chat_response(chat) async def get_chat(self, chat_id: int, user_id: int) -> ChatResponse: chat = await chat_storage.get_chat(chat_id) if user_id not in [user.id for user in chat.users]: not_a_member_of_chat() return await self.build_chat_response(chat) async def get_chats(self, user_id: int) -> list[ChatResponse]: chats = await chat_storage.get_chats(user_id) return [await self.build_chat_response(chat) for chat in chats]