package syncz

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func Test_SyncWorkerHolder_StopNoop(t *testing.T) {
	factCalled := 0
	stopCalled := 0
	w := NewComparableSyncWorkerHolder[string](func(s string) func() {
		factCalled++
		return func() {
			stopCalled++
		}
	})

	w.Stop()

	assert.Zero(t, factCalled)
	assert.Zero(t, stopCalled)
}

func Test_SyncWorkerHolder_SingleValue(t *testing.T) {
	factCalled := 0
	stopCalled := 0
	got := ""
	w := NewComparableSyncWorkerHolder[string](func(s string) func() {
		factCalled++
		got = s
		return func() {
			stopCalled++
		}
	})

	w.ApplyConfig("test")
	assert.Equal(t, "test", got)
	assert.Equal(t, 1, factCalled)
	assert.Zero(t, stopCalled)
	w.Stop()
	assert.Equal(t, 1, stopCalled)
}

func Test_SyncWorkerHolder_Duplicate(t *testing.T) {
	factCalled := 0
	stopCalled := 0
	got := ""
	w := NewComparableSyncWorkerHolder[string](func(s string) func() {
		factCalled++
		got = s
		return func() {
			stopCalled++
		}
	})

	w.ApplyConfig("test")
	w.ApplyConfig("test")

	assert.Equal(t, "test", got)
	assert.Equal(t, 1, factCalled)
	assert.Zero(t, stopCalled)
	w.Stop()
	assert.Equal(t, 1, stopCalled)
}

func Test_SyncWorkerHolder_NewValue(t *testing.T) {
	factCalled := 0
	stopCalled := 0
	got := ""
	w := NewComparableSyncWorkerHolder[string](func(s string) func() {
		factCalled++
		got = s
		return func() {
			stopCalled++
		}
	})

	w.ApplyConfig("a")
	w.ApplyConfig("b")

	assert.Equal(t, "b", got)
	assert.Equal(t, 2, factCalled)
	assert.Equal(t, 1, stopCalled)
	w.Stop()
	assert.Equal(t, 2, stopCalled)
}
