"""会话路由。""" from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel, Field from api.deps import current_actor, session_service from api.response import ok from application.session_service import SessionService from domain.models import Actor router = APIRouter(prefix="/sessions", tags=["sessions"]) class CreateSessionBody(BaseModel): title: str | None = None class RenameBody(BaseModel): title: str = Field(min_length=1, max_length=200) def _session_vo(s) -> dict: return { "threadId": s.thread_id, "title": s.title, "status": s.status.value, "createdAt": s.created_at.isoformat() + "Z", "updatedAt": s.updated_at.isoformat() + "Z", "lastMessageAt": s.last_message_at.isoformat() + "Z" if s.last_message_at else None, } @router.get("") async def list_sessions( actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): rows = await svc.list_mine(actor) return ok({"items": [_session_vo(s) for s in rows]}) @router.post("") async def create_session( body: CreateSessionBody, actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): s = await svc.create(actor, body.title) return ok(_session_vo(s)) @router.patch("/{thread_id}") async def rename_session( thread_id: str, body: RenameBody, actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): try: s = await svc.rename(actor, thread_id, body.title) except LookupError as e: raise HTTPException(status_code=404, detail=str(e)) from e return ok(_session_vo(s)) @router.post("/{thread_id}/archive") async def archive_session( thread_id: str, actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): try: s = await svc.archive(actor, thread_id) except LookupError as e: raise HTTPException(status_code=404, detail=str(e)) from e return ok(_session_vo(s))