package filters

import (
	"strings"
	"sync"
)

type Rule struct {
	Topic string `json:"topic"`
	Save  bool   `json:"save"`
	View  bool   `json:"view"`
}

type Store struct {
	mu    sync.RWMutex
	rules []Rule
}

func NewStore() *Store {
	return &Store{rules: []Rule{}}
}

func (s *Store) Update(rules []Rule) {
	clean := make([]Rule, 0, len(rules))
	for _, rule := range rules {
		if strings.TrimSpace(rule.Topic) == "" {
			continue
		}
		clean = append(clean, rule)
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	s.rules = clean
}

func (s *Store) Snapshot() []Rule {
	s.mu.RLock()
	defer s.mu.RUnlock()
	out := make([]Rule, len(s.rules))
	copy(out, s.rules)
	return out
}

func (s *Store) Match(topic string) (Rule, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	for _, rule := range s.rules {
		if matchTopic(rule.Topic, topic) {
			return rule, true
		}
	}
	return Rule{}, false
}

func matchTopic(rule, topic string) bool {
	rule = strings.TrimSpace(rule)
	if rule == "" {
		return false
	}
	if rule == "#" {
		return true
	}
	if strings.HasSuffix(rule, "/#") {
		prefix := strings.TrimSuffix(rule, "/#")
		return strings.HasPrefix(topic, prefix)
	}
	return rule == topic
}
