package kas

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/featureflag"
	"google.golang.org/grpc/metadata"
)

func TestFeatureFlagsFromContext(t *testing.T) {
	// GIVEN
	tests := []struct {
		name         string
		featureFlags map[string]string
		expected     featureflag.Set
	}{
		{
			name:         "no feature flag headers",
			featureFlags: nil,
			expected:     featureflag.NewSet(nil, nil),
		},
		{
			name:         "single feature flag",
			featureFlags: map[string]string{ffNamePrefix + "some-ff": "true"},
			expected: featureflag.NewSet(map[string]bool{
				"some_ff": true,
			}, nil),
		},
		{
			name:         "multiple feature flags",
			featureFlags: map[string]string{ffNamePrefix + "some-ff": "true", ffNamePrefix + "another-ff": "true"},
			expected: featureflag.NewSet(map[string]bool{
				"some_ff":    true,
				"another_ff": true,
			}, nil),
		},
		{
			name:         "multiple feature one disabled",
			featureFlags: map[string]string{ffNamePrefix + "some-ff": "true", ffNamePrefix + "another-ff": "false"},
			expected: featureflag.NewSet(map[string]bool{
				"some_ff":    true,
				"another_ff": false,
			}, nil),
		},
		{
			name:         "feature flag with non-boolean value is ignored",
			featureFlags: map[string]string{ffNamePrefix + "some-ff": "true", ffNamePrefix + "another-ff": "foo"},
			expected: featureflag.NewSet(map[string]bool{
				"some_ff": true,
			}, nil),
		},
		{
			name:         "feature flag with non-boolean value is ignored - empty",
			featureFlags: map[string]string{ffNamePrefix + "another-ff": "foo"},
			expected:     featureflag.NewSet(nil, nil),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// GIVEN
			ctx := metadata.NewIncomingContext(t.Context(), metadata.New(tt.featureFlags))

			// WHEN
			s := featureFlagsFromContext(ctx, nil)

			// THEN
			assert.Equal(t, tt.expected, s)
		})
	}
}

func TestMetadata_FromContext_NilMetadata(t *testing.T) {
	// GIVEN
	ctx := metadata.NewIncomingContext(t.Context(), nil)

	// WHEN
	s := featureFlagsFromContext(ctx, nil)

	// THEN
	assert.Equal(t, featureflag.NewSet(nil, nil), s)
}

func TestMetadata_FromContext_NoMetadata(t *testing.T) {
	// GIVEN
	ctx := t.Context()

	// WHEN
	s := featureFlagsFromContext(ctx, nil)

	// THEN
	assert.Equal(t, featureflag.NewSet(nil, nil), s)
}
