import re import uuid from fastapi import APIRouter, Depends, Header, HTTPException, Query, status from sqlalchemy.orm import Session from app.api.deps import get_db, get_current_user from app.db.models import User as UserModel from app.models import CreateMessage, Message as MessageResponse from app.services.message_service import ( MessageService, MessageNotFoundError, InvalidMessageDataError, IdempotencyConflictError, ) router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["Messages"]) IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") def message_to_response(message) -> MessageResponse: return MessageResponse( id=str(message.id), chat_id=str(message.chat_id), sender_id=str(message.sender_id), text=message.text, created_at=message.created_at, ) def parse_chat_id(chat_id: str) -> uuid.UUID: try: return uuid.UUID(chat_id) except ValueError: raise HTTPException(status_code=400, detail="Invalid chat UUID") from None @router.post("", response_model=MessageResponse, status_code=status.HTTP_201_CREATED) def create_message( chat_id: str, body: CreateMessage, idempotency_key: str = Header(..., alias="Idempotency-Key", min_length=1, max_length=128), db: Session = Depends(get_db), user: UserModel = Depends(get_current_user), ): if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key): raise HTTPException(status_code=400, detail="Invalid Idempotency-Key") parsed_id = parse_chat_id(chat_id) try: message = MessageService(db).create_message( chat_id=parsed_id, sender_id=user.id, text=body.text, idempotency_key=idempotency_key, ) return message_to_response(message) except MessageNotFoundError: raise HTTPException(status_code=404, detail="Chat not found") from None except InvalidMessageDataError as exc: raise HTTPException(status_code=400, detail=str(exc)) from None except IdempotencyConflictError: raise HTTPException(status_code=409, detail="Idempotency-Key was already used with a different request") from None @router.get("") def list_messages( chat_id: str, limit: int = Query(default=50, ge=1, le=100), cursor: str | None = None, db: Session = Depends(get_db), user: UserModel = Depends(get_current_user), ): parsed_id = parse_chat_id(chat_id) try: messages, next_cursor = MessageService(db).get_history( chat_id=parsed_id, user_id=user.id, limit=limit, cursor=cursor ) return {"items": [message_to_response(item) for item in messages], "next_cursor": next_cursor} except MessageNotFoundError: raise HTTPException(status_code=404, detail="Chat not found") from None except InvalidMessageDataError as exc: raise HTTPException(status_code=400, detail=str(exc)) from None