package util

import "k8s.io/utils/ptr"

// MergeMaps is a function that is authored (except the name) by Copilot.
// Deprecated: use github.com/tidbcloud/infra-provider/util instead
func MergeMaps[K comparable, V any](maps ...map[K]V) map[K]V {
	result := make(map[K]V)
	for _, m := range maps {
		for k, v := range m {
			result[k] = v
		}
	}
	return result
}

// MapSlice returns a new slice containing the results of applying the function f to each item in the original slice.
// Deprecated: use github.com/tidbcloud/infra-provider/util instead
func MapSlice[T any, O any](s []T, f func(e T) O) []O {
	r := make([]O, len(s))
	for i, e := range s {
		r[i] = f(e)
	}
	return r
}

// DeepCopyMap returns a deep copy of the given map.
// Note: the map's value cannot be a reference type (like slice or map).
// Deprecated: use github.com/tidbcloud/infra-provider/util instead
func DeepCopyMap[K comparable, V any](originalMap map[K]V) map[K]V {
	// Create a new map to store the copied key-value pairs with the same capacity as the original map
	copiedMap := make(map[K]V, len(originalMap))

	// Iterate over the original map's key-value pairs
	for key, value := range originalMap {
		// Add the key-value pair into the new map, since the value is not a reference type, it is safe to copy directly
		copiedMap[key] = value
	}

	// Return the deep copied map
	return copiedMap
}

// ToMapPointer converts a map with values of type V to a map with values of type *V.
// It creates a new map where each value is a pointer to the corresponding value in the original map.
// This is done to avoid using the same pointer address for each value in the new map.
// The function takes an originalMap as input, which is a map with keys of type K and values of type V.
// It returns a new map with keys of type K and values of type *V.
func ToMapPointer[K comparable, V any](originalMap map[K]V) map[K]*V {
	tags := make(map[K]*V, len(originalMap))
	for k, v := range originalMap {
		// ptr.To returns a pointer to the value passed in
		// we should use ptr.To instead of &v to avoid the same pointer address
		tags[k] = ptr.To(v)
	}
	return tags
}
