package store

import (
	"context"
	"testing"
	"time"
)

// One fact per kuma monitor means the loop cannot name its keys at wiring time,
// so it asks for the family by prefix. The read must return the newest row per
// key and stop at the prefix boundary.
func TestLatestFactsByPrefix(t *testing.T) {
	s := newTestStore(t)
	ctx := context.Background()
	now := time.Now().UTC().Truncate(time.Millisecond)
	write := func(key, val string, at time.Time) int64 {
		id, err := s.SetValue(ctx, KindEnv, key, "poll:uptimekuma", val, at)
		if err != nil {
			t.Fatalf("SetValue %s: %v", key, err)
		}
		return id
	}
	write("service_down:db", "up", now.Add(-2*time.Hour))
	write("service_down:db", "down", now.Add(-time.Hour)) // newer wins
	write("service_down:web", "up", now.Add(-time.Hour))
	write("service_downtime", "irrelevant", now) // no colon, not in the family
	write("water", "250ml", now)

	got, err := s.LatestFactsByPrefix(ctx, "service_down:")
	if err != nil {
		t.Fatalf("LatestFactsByPrefix: %v", err)
	}
	if len(got) != 2 {
		t.Fatalf("got %d facts, want 2: %+v", len(got), got)
	}
	if got[0].Key != "service_down:db" || got[0].Value != `"down"` {
		t.Errorf("first = %s=%s, want the newest db row", got[0].Key, got[0].Value)
	}
	if got[1].Key != "service_down:web" {
		t.Errorf("second = %s, want service_down:web", got[1].Key)
	}
}

// A monitor name is user text. An underscore in it must match itself, not act
// as a LIKE wildcard and drag in every other monitor.
func TestLatestFactsByPrefixEscapesWildcards(t *testing.T) {
	s := newTestStore(t)
	ctx := context.Background()
	now := time.Now().UTC().Truncate(time.Millisecond)
	for _, k := range []string{"a_b:one", "axb:two"} {
		if _, err := s.SetValue(ctx, KindEnv, k, "poll:uptimekuma", "down", now); err != nil {
			t.Fatalf("SetValue %s: %v", k, err)
		}
	}
	got, err := s.LatestFactsByPrefix(ctx, "a_b:")
	if err != nil {
		t.Fatalf("LatestFactsByPrefix: %v", err)
	}
	if len(got) != 1 || got[0].Key != "a_b:one" {
		t.Fatalf("got %+v, want only a_b:one", got)
	}
}
