from typing import Annotated from uuid import UUID from fastapi import APIRouter, Depends, Query, status from src.api.dependencies import get_chat_service, get_current_user from src.api.v1.routers.chats.schemas import ChatOut, CreateChatIn, GetChatOut from src.api.v1.schemas import PaginationQuery from src.core.errors import ApiError from src.core.pagination import decode_cursor, encode_cursor from src.service.chat import ChatService from src.service.dto import ChatDTO, UserDTO from src.service.exceptions import ChatNotFoundException, InvalidChatMembersException router = APIRouter(prefix="/chats", tags=["Чаты"]) def _to_chat_out(chat: ChatDTO) -> ChatOut: return ChatOut( id=chat.id, title=chat.title, member_ids=list(chat.member_ids), created_at=chat.created_at, ) @router.post("", status_code=status.HTTP_201_CREATED) async def create_chat( chat_in: CreateChatIn, current_user: Annotated[UserDTO, Depends(get_current_user)], chat_service: Annotated[ChatService, Depends(get_chat_service)], ) -> ChatOut: try: chat = await chat_service.create_chat( title=chat_in.title, member_ids=chat_in.member_ids, current_user_id=current_user.id, ) except InvalidChatMembersException as error: raise ApiError(400, "invalid_request", str(error)) from error return _to_chat_out(chat) @router.get("", status_code=status.HTTP_200_OK) async def get_chats( pagination: Annotated[PaginationQuery, Query()], current_user: Annotated[UserDTO, Depends(get_current_user)], chat_service: Annotated[ChatService, Depends(get_chat_service)], ) -> GetChatOut: after = None if pagination.cursor is not None: after = decode_cursor( pagination.cursor, expected_kind="chats", expected_owner_id=current_user.id, ) chats = await chat_service.get_chats( current_user_id=current_user.id, limit=pagination.limit + 1, after=after ) page = chats[: pagination.limit] next_cursor = None if len(chats) > pagination.limit: last = page[-1] next_cursor = encode_cursor("chats", current_user.id, last.created_at, last.id) return GetChatOut( items=[_to_chat_out(chat) for chat in page], next_cursor=next_cursor, ) @router.get("/{chat_id}", summary="Получить доступный чат") async def get_chat( chat_id: UUID, current_user: Annotated[UserDTO, Depends(get_current_user)], chat_service: Annotated[ChatService, Depends(get_chat_service)], ) -> ChatOut: try: chat = await chat_service.get_chat( chat_id=chat_id, current_user_id=current_user.id, ) except ChatNotFoundException as error: raise ApiError(404, "not_found", str(error)) from error return _to_chat_out(chat)