//go:build unit || all
// +build unit all

package util

import (
	"reflect"
	"testing"

	"k8s.io/utils/ptr"
)

func TestMergeMaps(t *testing.T) {
	type args struct {
		maps []map[string]string
	}
	tests := []struct {
		name string
		args args
		want map[string]string
	}{
		{
			name: "empty",
			args: args{
				maps: []map[string]string{},
			},
			want: map[string]string{},
		},
		{
			name: "one",
			args: args{
				maps: []map[string]string{
					{
						"a": "b",
					},
				},
			},
			want: map[string]string{
				"a": "b",
			},
		},
		{
			name: "two",
			args: args{
				maps: []map[string]string{
					{
						"a": "b",
					},
					{
						"c": "d",
					},
				},
			},
			want: map[string]string{
				"a": "b",
				"c": "d",
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := MergeMaps(tt.args.maps...); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("MergeMaps() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestDeepCopyMap(t *testing.T) {
	tests := []struct {
		name           string
		originalMap    map[string]string
		expectedMap    map[string]string
		modifyOriginal func(mapToModify map[string]string)
	}{
		{
			name:        "string keys, string values",
			originalMap: map[string]string{"one": "first", "two": "second"},
			expectedMap: map[string]string{"one": "first", "two": "second"},
			modifyOriginal: func(mapToModify map[string]string) {
				mapToModify["one"] = "modified"
				mapToModify["three"] = "third"
			},
		},
		{
			name:           "empty map",
			originalMap:    map[string]string{},
			expectedMap:    map[string]string{},
			modifyOriginal: func(mapToModify map[string]string) {},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			copiedMap := DeepCopyMap(tt.originalMap)

			if !reflect.DeepEqual(copiedMap, tt.expectedMap) {
				t.Errorf("DeepCopyMap() returned %v, expected %v", copiedMap, tt.expectedMap)
			}

			// Modify the original map
			tt.modifyOriginal(tt.originalMap)

			// Check if the copied map is still the same as expected
			if !reflect.DeepEqual(copiedMap, tt.expectedMap) {
				t.Errorf("Copied map was affected after modifying original map, returned %v, expected %v", copiedMap, tt.expectedMap)
			}
		})
	}
}

func Test_ToMapPointer(t *testing.T) {
	mp := map[string]string{
		"key1": "value1",
		"key2": "value2",
		"key3": "value3",
	}

	expectedTags := map[string]*string{
		"key1": ptr.To("value1"),
		"key2": ptr.To("value2"),
		"key3": ptr.To("value3"),
	}

	tags := ToMapPointer(mp)

	if !reflect.DeepEqual(tags, expectedTags) {
		t.Errorf("ToMapPointer() returned %v, expected %v", tags, expectedTags)
	}
}
