package globalservice

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes/fake"
)

// TestWatchBehavior demonstrates the improved watch implementation
func TestWatchBehavior(t *testing.T) {
	// Create a fake Kubernetes client
	fakeClient := fake.NewSimpleClientset()

	// Create a test ConfigMap
	testCM := &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test-configmap",
			Namespace: "test-namespace",
		},
		Data: map[string]string{
			"meta.json": `{"test": "data"}`,
		},
	}

	_, err := fakeClient.CoreV1().ConfigMaps("test-namespace").Create(
		context.Background(), testCM, metav1.CreateOptions{})
	assert.NoError(t, err)

	// Test the watch functionality
	watcher, err := fakeClient.CoreV1().ConfigMaps("test-namespace").Watch(
		context.Background(), metav1.ListOptions{
			FieldSelector: "metadata.name=test-configmap",
		})
	assert.NoError(t, err)
	defer watcher.Stop()

	// Simulate a change
	go func() {
		time.Sleep(100 * time.Millisecond)
		testCM.Data["meta.json"] = `{"test": "updated"}`
		_, _ = fakeClient.CoreV1().ConfigMaps("test-namespace").Update(
			context.Background(), testCM, metav1.UpdateOptions{})
	}()

	// Wait for the watch event
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	select {
	case event := <-watcher.ResultChan():
		assert.Equal(t, watch.Modified, event.Type)
		t.Logf("Received expected watch event: %s", event.Type)
	case <-ctx.Done():
		t.Fatal("Timeout waiting for watch event")
	}
}
