package memory import ( "context" "slices" "time" "github.com/google/uuid" "mtusi-messenger/internal/domain" ) type MessageRepository struct { store *Store } func (r *MessageRepository) Create(_ context.Context, draft domain.MessageDraft) (domain.Message, error) { s := r.store s.mu.Lock() defer s.mu.Unlock() chat, ok := s.chatsByID[draft.ChatID] if !ok || !chat.HasMember(draft.SenderID) { return domain.Message{}, domain.ErrNotFound } message := domain.Message{ ID: s.ids.NewID(), ChatID: draft.ChatID, SenderID: draft.SenderID, Text: draft.Text, CreatedAt: s.clock.Now(), } history := s.messagesByChat[message.ChatID] if len(history) == 0 || compareKeyset( history[len(history)-1].CreatedAt, history[len(history)-1].ID, message.CreatedAt, message.ID, ) < 0 { s.messagesByChat[message.ChatID] = append(history, message) return message, nil } at, _ := slices.BinarySearchFunc(history, message, func(a, b domain.Message) int { return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID) }) s.messagesByChat[message.ChatID] = slices.Insert(history, at, message) return message, nil } func (r *MessageRepository) ListVisible( _ context.Context, chatID, callerID uuid.UUID, after *domain.Cursor, limit int, ) (domain.Page[domain.Message], error) { s := r.store s.mu.RLock() defer s.mu.RUnlock() chat, ok := s.chatsByID[chatID] if !ok || !chat.HasMember(callerID) { return domain.Page[domain.Message]{}, domain.ErrNotFound } return paginate(s.messagesByChat[chatID], chatID, messageKey, after, limit), nil } func messageKey(message domain.Message) (time.Time, uuid.UUID) { return message.CreatedAt, message.ID }