package rpc

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool"
	"google.golang.org/grpc/metadata"
)

func MetadataKVToMeta(from []*MetadataKV) metadata.MD {
	return tool.SliceToMap[string, string, *MetadataKV, []string, []*MetadataKV, metadata.MD](
		from,
		func(v *MetadataKV) int {
			return len(v.Value.Value)
		},
		func(kv *MetadataKV, sink []string) []string {
			for _, v := range kv.Value.Value {
				sink = append(sink, string(v))
			}
			return sink
		},
		func(kv *MetadataKV, elem []string) (string, []string) {
			return string(kv.Key), elem
		},
	)
}

func MetaToMetadataKV(from metadata.MD) []*MetadataKV {
	return tool.StringMapToSliceWithBytes[*MetadataKV, metadata.MD, []*MetadataKV](
		from,
		func(key string, elem [][]byte) *MetadataKV {
			return &MetadataKV{
				Key: []byte(key),
				Value: &MetadataValues{
					Value: elem,
				},
			}
		},
	)
}
