import uuid from datetime import datetime from fastapi import APIRouter, HTTPException, Depends from pydantic import BaseModel, Field, ConfigDict, field_serializer from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.models.message import Message from app.models.chat import Chat, ChatMember from app.models.user import User from app.security import get_current_user from app.dependencies import get_session from app.pagination import paginate router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"]) class CreateMessage(BaseModel): model_config = ConfigDict(extra="forbid") text: str = Field(min_length=1, max_length=4000) class MessageResponse(BaseModel): id: uuid.UUID chat_id: uuid.UUID sender_id: uuid.UUID text: str created_at: datetime model_config = ConfigDict(from_attributes=True) @field_serializer('created_at') def serialize_dt(self, dt: datetime): return dt.isoformat().replace("+00:00", "Z") async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession): chat = await session.get(Chat, chat_id) if not chat: raise HTTPException(status_code=404, detail="чат не найден") result = await session.execute( select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id) ) if not result.scalar_one_or_none(): raise HTTPException(status_code=404, detail="чат не найден") return chat @router.post("", status_code=201, response_model=MessageResponse) async def create_message( chat_id: str, payload: CreateMessage, user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session) ): await check_chat_access(chat_id, user.id, session) message = Message( chat_id=chat_id, sender_id=user.id, text=payload.text ) session.add(message) await session.commit() await session.refresh(message) return message @router.get("") async def list_messages( chat_id: str, limit: int = 50, cursor: str | None = None, user: User = Depends(get_current_user), session: AsyncSession = Depends(get_session) ): if limit < 1 or limit > 100: raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100") await check_chat_access(chat_id, user.id, session) result = await session.execute( select(Message) .where(Message.chat_id == chat_id) .order_by(Message.created_at, Message.id) ) msgs = result.scalars().all() my_messages = [ { "id": m.id, "chat_id": m.chat_id, "sender_id": m.sender_id, "text": m.text, "created_at": m.created_at.isoformat().replace("+00:00", "Z"), } for m in msgs ] page, next_cursor = paginate(my_messages, limit, cursor) return {"items": page, "next_cursor": next_cursor}