"""PostgreSQL repository functions for MTUSI Messenger Lab2.""" from __future__ import annotations from collections.abc import Iterable from datetime import datetime from typing import Any from uuid import UUID, uuid4 from sqlalchemy import text from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession async def create_user( db: AsyncSession, *, username: str, display_name: str, password_hash: str, ) -> dict[str, Any] | None: user_id = uuid4() try: result = await db.execute( text( """ INSERT INTO users (id, username, display_name, password_hash) VALUES (:id, :username, :display_name, :password_hash) RETURNING id, username, display_name, created_at """ ), { "id": user_id, "username": username, "display_name": display_name, "password_hash": password_hash, }, ) await db.commit() return dict(result.mappings().one()) except IntegrityError: await db.rollback() return None async def get_user_by_username( db: AsyncSession, username: str, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = :username """ ), {"username": username}, ) row = result.mappings().first() return dict(row) if row is not None else None async def get_user_by_id( db: AsyncSession, user_id: UUID, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT id, username, display_name, created_at FROM users WHERE id = :user_id """ ), {"user_id": user_id}, ) row = result.mappings().first() return dict(row) if row is not None else None async def user_ids_that_exist( db: AsyncSession, member_ids: Iterable[UUID], ) -> set[UUID]: values = list(member_ids) if not values: return set() result = await db.execute( text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"), {"member_ids": values}, ) return {row.id for row in result} async def create_session( db: AsyncSession, *, user_id: UUID, token_hash: str, expires_at: datetime, ) -> None: await db.execute( text( """ INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES (:id, :user_id, :token_hash, :expires_at) """ ), { "id": uuid4(), "user_id": user_id, "token_hash": token_hash, "expires_at": expires_at, }, ) await db.commit() async def get_active_session_user( db: AsyncSession, token_hash: str, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT s.id AS session_id, s.token_hash, s.expires_at, u.id, u.username, u.display_name, u.created_at FROM sessions AS s JOIN users AS u ON u.id = s.user_id WHERE s.token_hash = :token_hash AND s.revoked_at IS NULL AND s.expires_at > now() """ ), {"token_hash": token_hash}, ) row = result.mappings().first() return dict(row) if row is not None else None async def revoke_active_session( db: AsyncSession, token_hash: str, ) -> bool: result = await db.execute( text( """ UPDATE sessions SET revoked_at = now() WHERE token_hash = :token_hash AND revoked_at IS NULL AND expires_at > now() """ ), {"token_hash": token_hash}, ) await db.commit() return result.rowcount == 1 async def create_chat_with_members( db: AsyncSession, *, title: str, member_ids: Iterable[UUID], ) -> dict[str, Any]: chat_id = uuid4() members = list(member_ids) try: result = await db.execute( text( """ INSERT INTO chats (id, title) VALUES (:id, :title) RETURNING id, title, created_at """ ), {"id": chat_id, "title": title}, ) chat = dict(result.mappings().one()) await db.execute( text( """ INSERT INTO chat_members (chat_id, user_id) VALUES (:chat_id, :user_id) """ ), [{"chat_id": chat_id, "user_id": user_id} for user_id in members], ) await db.commit() except Exception: await db.rollback() raise chat["member_ids"] = members return chat async def get_accessible_chat( db: AsyncSession, *, chat_id: UUID, user_id: UUID, ) -> dict[str, Any] | None: result = await db.execute( text( """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS own_membership ON own_membership.chat_id = c.id AND own_membership.user_id = :user_id WHERE c.id = :chat_id """ ), {"chat_id": chat_id, "user_id": user_id}, ) chat_row = result.mappings().first() if chat_row is None: return None members_result = await db.execute( text( """ SELECT user_id FROM chat_members WHERE chat_id = :chat_id ORDER BY user_id ASC """ ), {"chat_id": chat_id}, ) chat = dict(chat_row) chat["member_ids"] = [row.user_id for row in members_result] return chat async def list_chats_for_user( db: AsyncSession, *, user_id: UUID, limit: int, cursor_created_at: datetime | None, cursor_id: UUID | None, ) -> list[dict[str, Any]]: query = """ SELECT c.id, c.title, c.created_at FROM chats AS c JOIN chat_members AS own_membership ON own_membership.chat_id = c.id AND own_membership.user_id = :user_id \ """ params: dict[str, Any] = { "user_id": user_id, "limit_plus_one": limit + 1, } if cursor_created_at is not None and cursor_id is not None: query += """ WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id) """ params["cursor_created_at"] = cursor_created_at params["cursor_id"] = cursor_id query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one" result = await db.execute(text(query), params) chats = [dict(row) for row in result.mappings().all()] if not chats: return [] chat_ids = [chat["id"] for chat in chats] members_result = await db.execute( text( """ SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY(CAST(:chat_ids AS uuid[])) ORDER BY chat_id ASC, user_id ASC """ ), {"chat_ids": chat_ids}, ) members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids} for row in members_result: members_by_chat[row.chat_id].append(row.user_id) for chat in chats: chat["member_ids"] = members_by_chat[chat["id"]] return chats async def create_message( db: AsyncSession, *, chat_id: UUID, sender_id: UUID, text_value: str, ) -> dict[str, Any]: message_id = uuid4() result = await db.execute( text( """ INSERT INTO messages (id, chat_id, sender_id, text) VALUES (:id, :chat_id, :sender_id, :text) RETURNING id, chat_id, sender_id, text, created_at """ ), { "id": message_id, "chat_id": chat_id, "sender_id": sender_id, "text": text_value, }, ) await db.commit() return dict(result.mappings().one()) async def list_messages_keyset( db: AsyncSession, *, chat_id: UUID, limit: int, cursor_created_at: datetime | None, cursor_id: UUID | None, ) -> list[dict[str, Any]]: query = """ SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = :chat_id \ """ params: dict[str, Any] = { "chat_id": chat_id, "limit_plus_one": limit + 1, } if cursor_created_at is not None and cursor_id is not None: query += """ AND (created_at, id) > (:cursor_created_at, :cursor_id) """ params["cursor_created_at"] = cursor_created_at params["cursor_id"] = cursor_id query += " ORDER BY created_at ASC, id ASC LIMIT :limit_plus_one" result = await db.execute(text(query), params) return [dict(row) for row in result.mappings().all()]