package server

import (
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testhelpers"
	"google.golang.org/grpc/metadata"
)

func TestPrepareMetadata_HandlesNilMD(t *testing.T) {
	md := prepareMetadata(testhelpers.AgentkKey1, nil)
	assert.Equal(t, metadata.MD{
		agentIDMDKey:   []string{strconv.FormatInt(testhelpers.AgentkKey1.ID, 10)},
		agentTypeMDKey: []string{testhelpers.AgentkKey1.Type.String()},
	}, md)
}

func TestPrepareMetadata_HandlesEmptyMD(t *testing.T) {
	md := prepareMetadata(testhelpers.AgentkKey1, metadata.MD{})
	assert.Equal(t, metadata.MD{
		agentIDMDKey:   []string{strconv.FormatInt(testhelpers.AgentkKey1.ID, 10)},
		agentTypeMDKey: []string{testhelpers.AgentkKey1.Type.String()},
	}, md)
}

func TestPrepareMetadata_HappyPath(t *testing.T) {
	md := prepareMetadata(testhelpers.AgentkKey1, metadata.MD{"some-key": []string{"abc"}})
	assert.Equal(t, metadata.MD{
		"some-key":     []string{"abc"},
		agentIDMDKey:   []string{strconv.FormatInt(testhelpers.AgentkKey1.ID, 10)},
		agentTypeMDKey: []string{testhelpers.AgentkKey1.Type.String()},
	}, md)
}

func TestPrepareMetadata_OverwritesRougeKey(t *testing.T) {
	md := prepareMetadata(testhelpers.AgentkKey1, metadata.MD{agentIDMDKey: []string{"333"}})
	assert.Equal(t, metadata.MD{
		agentIDMDKey:   []string{strconv.FormatInt(testhelpers.AgentkKey1.ID, 10)},
		agentTypeMDKey: []string{testhelpers.AgentkKey1.Type.String()},
	}, md)
}
