package sysinfo

import (
	"strings"
	"sync"
)

type Snapshot struct {
	Version       string `json:"version"`
	Clients       string `json:"clients"`
	MsgReceived   string `json:"msgReceived"`
	MsgSent       string `json:"msgSent"`
	MsgStored     string `json:"msgStored"`
	Subscriptions string `json:"subscriptions"`
}

type Store struct {
	mu   sync.RWMutex
	data Snapshot
}

func NewStore() *Store {
	return &Store{}
}

func (s *Store) Update(topic string, payload string) {
	trimmed := strings.TrimSpace(payload)
	if trimmed == "" {
		return
	}
	key := strings.TrimPrefix(topic, "$SYS/broker/")

	s.mu.Lock()
	defer s.mu.Unlock()
	switch key {
	case "version":
		s.data.Version = trimmed
	case "clients/connected":
		s.data.Clients = trimmed
	case "messages/received":
		s.data.MsgReceived = trimmed
	case "messages/sent":
		s.data.MsgSent = trimmed
	case "messages/stored":
		s.data.MsgStored = trimmed
	case "subscriptions/count":
		s.data.Subscriptions = trimmed
	}
}

func (s *Store) Snapshot() Snapshot {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.data
}
