package memory import ( "context" "slices" "sort" "github.com/google/uuid" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto" "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store" ) // copyChat copies the membership slice to keep stored chat state private. func copyChat(c dto.ChatDTO) dto.ChatDTO { c.MemberIDs = slices.Clone(c.MemberIDs) return c } // CreateChat stores the chat and its member index atomically. func (s *Store) CreateChat(_ context.Context, c dto.ChatDTO) (dto.ChatDTO, error) { s.mu.Lock() defer s.mu.Unlock() for _, id := range c.MemberIDs { if _, ok := s.users[id]; !ok { return dto.ChatDTO{}, store.ErrNotFound } } if len(s.chats) >= s.limits.MaxChats || !s.reserve(chatCost(c)) { return dto.ChatDTO{}, store.ErrCapacity } c.CreatedAt = s.timestamp() c = copyChat(c) s.chats[c.ID] = c for _, id := range c.MemberIDs { s.userChats[id] = append(s.userChats[id], c) } return copyChat(c), nil } // Chat retrieves a defensive copy. Authorization belongs to the service. func (s *Store) Chat(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) { s.mu.RLock() defer s.mu.RUnlock() c, ok := s.chats[id] if !ok { return c, store.ErrNotFound } return copyChat(c), nil } // Chats uses the per-member index and binary search, without scanning other chats. func (s *Store) Chats(_ context.Context, user uuid.UUID, p dto.PositionDTO, limit int) ([]dto.ChatDTO, error) { s.mu.RLock() defer s.mu.RUnlock() all := s.userChats[user] i := sort.Search(len(all), func(i int) bool { return after(all[i].CreatedAt, all[i].ID, p) }) end := min(len(all), i+limit) out := make([]dto.ChatDTO, 0, end-i) for _, c := range all[i:end] { out = append(out, copyChat(c)) } return out, nil }