package agent

import (
	"bytes"
	"context"
	"log/slog"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/syncz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testhelpers"
)

func TestAgentKeyHandler(t *testing.T) {
	b := &bytes.Buffer{}
	agentKey := syncz.NewValueHolder[api.AgentKey]()
	h := &agentKeyHandler{
		delegate: slog.NewTextHandler(b, &slog.HandlerOptions{}),
		agentKey: agentKey,
	}
	r := slog.NewRecord(time.Time{}, slog.LevelInfo, "test", 0)
	err := h.Handle(context.Background(), r)
	require.NoError(t, err)

	err = agentKey.Set(testhelpers.AgentkKey1)
	require.NoError(t, err)

	err = h.Handle(context.Background(), r)
	require.NoError(t, err)

	expected := "level=INFO msg=test\nlevel=INFO msg=test agent_key=agentk:123\n"

	assert.Equal(t, expected, b.String())
}
