package web

import (
	"path/filepath"
	"strings"
	"testing"

	"pete/internal/storage"
)

func TestDisabledSourcesFor(t *testing.T) {
	storage.Close()
	if err := storage.Init(filepath.Join(t.TempDir(), "push.db")); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { storage.Close() })

	// The stored blob mirrors localStorage: the disabledSources value is itself a
	// JSON *string* encoding a {source: true} map (see prefs.js snapshot()).
	blob := `{"pete.disabledSources.v1":"{\"Feed A\":true,\"Feed B\":false}","pete.weather.loc.v1":"1000-100"}`
	if err := storage.PutUserPrefs("sub-1", blob, "u", "u@x"); err != nil {
		t.Fatal(err)
	}

	got := disabledSourcesFor("sub-1")
	if !got["Feed A"] {
		t.Error("Feed A should be disabled")
	}
	if got["Feed B"] {
		t.Error("Feed B is false in prefs and must not be treated as disabled")
	}
	if len(got) != 1 {
		t.Errorf("disabled set = %v, want just {Feed A}", got)
	}

	// A user with no prefs disables nothing.
	if len(disabledSourcesFor("nobody")) != 0 {
		t.Error("unknown user should have an empty disabled set")
	}
}

func TestBuildDigestPayload(t *testing.T) {
	single := string(buildDigestPayload(1, "Only Story"))
	if !strings.Contains(single, "1 new story") || strings.Contains(single, "1 new stories") {
		t.Errorf("singular wording wrong: %s", single)
	}
	if !strings.Contains(single, "Only Story") {
		t.Errorf("top headline missing: %s", single)
	}

	many := string(buildDigestPayload(7, "Big One"))
	if !strings.Contains(many, "7 new stories") || !strings.Contains(many, "Big One") {
		t.Errorf("plural payload wrong: %s", many)
	}
	if !strings.Contains(many, `"tag":"pete-digest"`) {
		t.Errorf("expected digest tag in payload: %s", many)
	}
}
