package mock_tunnel_rpc

import (
	"bytes"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tunnel/rpc"
	"google.golang.org/protobuf/testing/protocmp"
)

func EquateMetadataKV() cmp.Option {
	return cmp.Options{
		protocmp.SortRepeated(sortMetadataKV), // sort when *rpc.MetadataKV is part of a proto message
		cmpopts.SortSlices(sortMetadataKV),    // sort when *rpc.MetadataKV is not part of a proto message
	}
}

func sortMetadataKV(x, y *rpc.MetadataKV) bool {
	if x == y { // both nil or equal pointers
		return false // not less
	}
	if x == nil && y != nil {
		return true // nil < non-nil
	}
	if x != nil && y == nil {
		return false // not less
	}
	return bytes.Compare(x.Key, y.Key) == -1
}

func NewMetadataKV(key string, values ...string) *rpc.MetadataKV {
	v := make([][]byte, 0, len(values))
	for _, val := range values {
		v = append(v, []byte(val))
	}
	return &rpc.MetadataKV{
		Key: []byte(key),
		Value: &rpc.MetadataValues{
			Value: v,
		},
	}
}
