package store import ( "context" "errors" "time" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) // CreateChat inserts the chat and every membership row in one transaction. // Any unknown member aborts the whole transaction, so a partially created chat // can never be observed. func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return model.Chat{}, dbError(err) } defer func() { _ = tx.Rollback(context.Background()) }() for _, memberID := range memberIDs { var exists int err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists) if errors.Is(err, pgx.ErrNoRows) { return model.Chat{}, common.BadRequest("member_id refers to non-existent user") } if err != nil { return model.Chat{}, dbError(err) } } chat := model.Chat{ ID: uuid.New(), Title: title, MemberIDs: append([]uuid.UUID(nil), memberIDs...), CreatedAt: common.NowUTC(), } if _, err = tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil { return model.Chat{}, dbError(err) } for _, memberID := range memberIDs { if _, err = tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, chat.ID, memberID); err != nil { return model.Chat{}, dbError(err) } } if err = tx.Commit(ctx); err != nil { return model.Chat{}, dbError(err) } return chat, nil } func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() chat, err := scanChat(s.pool.QueryRow(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 WHERE c.id = $1`, chatID, userID)) if errors.Is(err, pgx.ErrNoRows) { return model.Chat{}, common.NotFound("chat not found") } if err != nil { return model.Chat{}, dbError(err) } return chat, nil } func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) { ctx, cancel := s.withTimeout(ctx) defer cancel() cursorTime, cursorID := cursorValues(cursor) rows, err := s.pool.Query(ctx, ` SELECT c.id, c.title, c.created_at, ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 WHERE (c.created_at, c.id) > ($2, $3) ORDER BY c.created_at, c.id LIMIT $4`, userID, cursorTime, cursorID, limit+1) if err != nil { return nil, dbError(err) } defer rows.Close() chats := make([]model.Chat, 0, limit) for rows.Next() { chat, scanErr := scanChat(rows) if scanErr != nil { return nil, dbError(scanErr) } chats = append(chats, chat) } if err = rows.Err(); err != nil { return nil, dbError(err) } hasMore := len(chats) > limit if hasMore { chats = chats[:limit] } return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil } func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() var exists int err := s.pool.QueryRow(ctx, `SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&exists) if errors.Is(err, pgx.ErrNoRows) { return false, nil } if err != nil { return false, dbError(err) } return true, nil } func scanChat(row rowScanner) (model.Chat, error) { var chat model.Chat var createdAt time.Time if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil { return model.Chat{}, err } chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) return chat, nil }