package agentbuild

import (
	"testing"

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

func TestO11yTolerations(t *testing.T) {
	tests := []struct {
		name      string
		projectID string
		want      map[string]any
	}{
		{
			name: "dedicated returns correct toleration",
			want: map[string]any{
				"key":      "o11y-dedicated",
				"operator": "Equal",
				"value":    "o11y",
				"effect":   "NoExecute",
			},
		},
		{
			name:      "project embeds projectID",
			projectID: "proj-123",
			want: map[string]any{
				"key":      "o11y-project",
				"operator": "Equal",
				"value":    "proj-123",
				"effect":   "NoExecute",
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var got map[string]any
			if tt.projectID != "" {
				got = O11yProjectToleration(tt.projectID)
			} else {
				got = O11yDedicatedToleration()
			}
			assert.Equal(t, tt.want, got)
		})
	}
}

func TestMergeOperatorChartValues(t *testing.T) {
	tests := []struct {
		name               string
		values             map[string]any
		wantTolerationKeys []string
		wantKeepExisting   bool
		wantNoMutation     bool
		wantLen            int
	}{
		{
			name:               "injects tolerations when absent",
			values:             map[string]any{"image": "test:1.0"},
			wantTolerationKeys: []string{"o11y-dedicated", "o11y-project"},
			wantLen:            2,
		},
		{
			name:             "keeps existing tolerations",
			values:           map[string]any{"tolerations": []map[string]any{{"key": "custom"}}},
			wantKeepExisting: true,
		},
		{
			name:           "does not mutate input",
			values:         map[string]any{"image": "test:1.0"},
			wantNoMutation: true,
		},
		{
			name:    "empty values gets only tolerations",
			values:  map[string]any{},
			wantLen: 1,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := MergeOperatorChartValues(tt.values, "proj-1")

			if tt.wantKeepExisting {
				existing := tt.values["tolerations"]
				assert.Equal(t, existing, got["tolerations"])
				return
			}
			if tt.wantNoMutation {
				_, hadKey := tt.values["tolerations"]
				assert.False(t, hadKey, "input map should not be mutated")
				assert.Contains(t, got, "tolerations")
				return
			}

			assert.Equal(t, tt.wantLen, len(got))
			if tt.wantTolerationKeys != nil {
				tolerations, ok := got["tolerations"].([]map[string]any)
				assert.True(t, ok)
				assert.Len(t, tolerations, len(tt.wantTolerationKeys))
				for i, key := range tt.wantTolerationKeys {
					assert.Equal(t, key, tolerations[i]["key"])
				}
				assert.Equal(t, "proj-1", tolerations[1]["value"])
			}
		})
	}
}
