package servervar

import (
	"context"
	"testing"
	"time"

	"github.com/uopi/uopi/internal/datasource"
)

func TestWriteSubscribePersist(t *testing.T) {
	dir := t.TempDir()
	s, err := New(dir)
	if err != nil {
		t.Fatalf("New: %v", err)
	}
	ctx := context.Background()

	if err := s.Write(ctx, "seq_state", 3.0); err != nil {
		t.Fatalf("Write: %v", err)
	}

	// Subscribe should deliver the current value immediately.
	ch := make(chan datasource.Value, 4)
	cancel, err := s.Subscribe(ctx, "seq_state", ch)
	if err != nil {
		t.Fatalf("Subscribe: %v", err)
	}
	defer cancel()
	select {
	case v := <-ch:
		if got := v.Data.(float64); got != 3.0 {
			t.Fatalf("initial value = %v, want 3", got)
		}
	case <-time.After(time.Second):
		t.Fatal("no initial value delivered")
	}

	// A later write fans out to the subscriber.
	if err := s.Write(ctx, "seq_state", 7.0); err != nil {
		t.Fatalf("Write 2: %v", err)
	}
	select {
	case v := <-ch:
		if got := v.Data.(float64); got != 7.0 {
			t.Fatalf("updated value = %v, want 7", got)
		}
	case <-time.After(time.Second):
		t.Fatal("no update delivered")
	}

	// ListSignals reports the variable.
	sigs, err := s.ListSignals(ctx)
	if err != nil || len(sigs) != 1 || sigs[0].Name != "seq_state" {
		t.Fatalf("ListSignals = %+v, err %v", sigs, err)
	}

	// A fresh store over the same dir recovers the last value.
	s2, err := New(dir)
	if err != nil {
		t.Fatalf("reopen: %v", err)
	}
	ch2 := make(chan datasource.Value, 1)
	cancel2, _ := s2.Subscribe(ctx, "seq_state", ch2)
	defer cancel2()
	select {
	case v := <-ch2:
		if got := v.Data.(float64); got != 7.0 {
			t.Fatalf("persisted value = %v, want 7", got)
		}
	case <-time.After(time.Second):
		t.Fatal("persisted value not delivered")
	}
}
