package gitlab

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/featureflag"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/httpz"
)

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

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// GIVEN
			var s featureflag.Set

			// WHEN
			featureFlagsHandlerFunc(&s)(http.Header{httpz.GitlabFeatureFlagHeader: tt.featureFlags}, nil)

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

func TestWithFeatureFlags_NoFeatureFlagHeader(t *testing.T) {
	// GIVEN
	var s featureflag.Set

	// WHEN
	featureFlagsHandlerFunc(&s)(http.Header{}, nil)

	// THEN
	assert.Empty(t, s)
}
