/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
 * KubernetesPlugin is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

// Package util provides shared helpers for tests.
package util

import "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

// PatchIntoFakeCR applies a merge-patch-like update into the in-memory fake CR used by tests.
func PatchIntoFakeCR(dst, patch *unstructured.Unstructured) {
	if dst == nil || patch == nil {
		return
	}
	dst.Object = mergeMaps(dst.Object, patch.Object)
}

func mergeMaps(dst, src map[string]interface{}) map[string]interface{} {
	if dst == nil {
		dst = make(map[string]interface{}, len(src))
	}
	for key, value := range src {
		srcMap, ok := value.(map[string]interface{})
		if ok {
			if dstMap, ok := dst[key].(map[string]interface{}); ok {
				dst[key] = mergeMaps(dstMap, srcMap)
				continue
			}
		}
		dst[key] = cloneValue(value)
	}
	return dst
}

func cloneValue(value interface{}) interface{} {
	switch v := value.(type) {
	case map[string]interface{}:
		return mergeMaps(nil, v)
	case []interface{}:
		out := make([]interface{}, len(v))
		for i, item := range v {
			out[i] = cloneValue(item)
		}
		return out
	default:
		return v
	}
}