"""Session service — chat sessions (each = one idea discussion).""" from uuid import uuid4 from sqlalchemy import select, update from sqlalchemy.ext.asyncio import AsyncSession from app.models.session import Session async def create_session( db: AsyncSession, user_id: str, title: str = "Новое обсуждение", ) -> Session: session = Session( id=uuid4(), user_id=user_id, title=title, status="active", ) db.add(session) await db.commit() await db.refresh(session) return session async def list_sessions( db: AsyncSession, user_id: str, status: str | None = None, limit: int = 50, offset: int = 0, ) -> list[Session]: stmt = ( select(Session) .where(Session.user_id == user_id) .order_by(Session.updated_at.desc()) .limit(limit) .offset(offset) ) if status: stmt = stmt.where(Session.status == status) result = await db.execute(stmt) return list(result.scalars().all()) async def get_session(db: AsyncSession, session_id: str) -> Session | None: result = await db.execute( select(Session).where(Session.id == session_id) ) return result.scalar_one_or_none() async def update_session_title( db: AsyncSession, session_id: str, title: str, ) -> bool: result = await db.execute( update(Session) .where(Session.id == session_id) .values(title=title) ) await db.commit() return result.rowcount > 0 async def update_session_idea( db: AsyncSession, session_id: str, idea_id: str, ) -> bool: result = await db.execute( update(Session) .where(Session.id == session_id) .values(idea_id=idea_id) ) await db.commit() return result.rowcount > 0 async def archive_session(db: AsyncSession, session_id: str) -> bool: result = await db.execute( update(Session) .where(Session.id == session_id) .values(status="archived") ) await db.commit() return result.rowcount > 0 async def delete_session(db: AsyncSession, session_id: str) -> bool: result = await db.execute( select(Session).where(Session.id == session_id) ) session = result.scalar_one_or_none() if not session: return False await db.delete(session) await db.commit() return True