package loop

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/kami/maven/internal/store"
)

// The gatherer is the only impure piece, and a rule over a prefix has no keys
// to declare at wiring time. This is the end of that path: mavpoll's per-monitor
// facts reach the snapshot, and the rule fires on the one that is down.
func TestGatherStateLoadsPrefixFamilies(t *testing.T) {
	ctx := context.Background()
	s, err := store.Open(ctx, filepath.Join(t.TempDir(), "loop_test.db"))
	if err != nil {
		t.Fatalf("Open: %v", err)
	}
	t.Cleanup(func() { _ = s.Close() })

	now := time.Now().UTC().Truncate(time.Millisecond)
	for key, val := range map[string]string{
		"service_down:db":  "down",
		"service_down:web": "up",
	} {
		// Older than MinDownAge, so this tests the gather path and not the
		// flap debounce.
		if _, err := s.SetValue(ctx, store.KindEnv, key, ServiceDownSource, val, now.Add(-5*time.Minute)); err != nil {
			t.Fatalf("SetValue %s: %v", key, err)
		}
	}

	rules := []Rule{ServiceDownRule()}
	st, _, err := NewGatherer(s, rules).GatherState(ctx, now)
	if err != nil {
		t.Fatalf("GatherState: %v", err)
	}
	if _, ok := st.Facts["service_down:db"]; !ok {
		t.Fatalf("prefix family not gathered: %v", st.Facts)
	}
	if got := DownServices(st); len(got) != 1 || got[0] != "db" {
		t.Fatalf("DownServices = %v, want [db]", got)
	}
	if !rules[0].Predicate(st) {
		t.Fatal("the rule must fire on a gathered per-monitor fact")
	}
}

func TestCollapseRemindersKeepsPersistedBundleSeparateFromNewDueRows(t *testing.T) {
	now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC)
	due := []store.Reminder{
		{ID: 1, FireTs: now, NextFireTs: now, Payload: "one", DeliveryGroup: "reminder:old", PhraseBody: "old bundle"},
		{ID: 2, FireTs: now.Add(time.Second), NextFireTs: now.Add(time.Second), Payload: "two", DeliveryGroup: "reminder:old", PhraseBody: "old bundle"},
		{ID: 3, FireTs: now.Add(2 * time.Second), NextFireTs: now.Add(2 * time.Second), Payload: "three"},
	}

	got := collapseReminders(due)
	if len(got) != 2 {
		t.Fatalf("deliveries = %d, want old bundle plus new reminder: %+v", len(got), got)
	}
	if got[0].ID != 0 || len(got[0].Collapsed) != 2 || got[0].Collapsed[0].ID != 1 || got[0].Collapsed[1].ID != 2 {
		t.Fatalf("old persisted bundle was changed: %+v", got[0])
	}
	if got[1].ID != 3 || len(got[1].Collapsed) != 0 {
		t.Fatalf("new reminder joined the old phrase: %+v", got[1])
	}
}

func TestCollapseRemindersMakesOneBundleForNewDueRows(t *testing.T) {
	now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC)
	due := []store.Reminder{
		{ID: 1, FireTs: now, NextFireTs: now, Payload: "one"},
		{ID: 2, FireTs: now, NextFireTs: now, Payload: "two"},
		{ID: 3, FireTs: now, NextFireTs: now, Payload: "three"},
	}
	got := collapseReminders(due)
	if len(got) != 1 || got[0].ID != 0 || len(got[0].Collapsed) != 3 {
		t.Fatalf("new reminders did not collapse together: %+v", got)
	}
}
