package api

import (
	"io"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/matcher"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/mock_gitlab"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testhelpers"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/agentcfg"
	"google.golang.org/protobuf/encoding/protojson"
)

func TestPostAgentConfiguration(t *testing.T) {
	config := &agentcfg.ConfigurationFile{
		Observability: &agentcfg.ObservabilityCF{
			Logging: &agentcfg.LoggingCF{
				Level: agentcfg.LogLevelEnum_info,
			},
		},
		// don't need to test all fields, some is good enough
	}
	ctx, traceID := testhelpers.CtxWithSpanContext(t)
	c := mock_gitlab.SetupClient(t, "", AgentConfigurationAPIPath, func(w http.ResponseWriter, r *http.Request) {
		testhelpers.AssertJWTSignature(t, r)
		testhelpers.AssertRequestMethod(t, r, http.MethodPost)
		testhelpers.AssertRequestContentTypeJSON(t, r)
		testhelpers.AssertCommonRequestParams(t, r, traceID)
		data, err := io.ReadAll(r.Body)
		if !assert.NoError(t, err) {
			return
		}
		actual := &AgentConfigurationRequest{
			AgentConfig: &agentcfg.ConfigurationFile{},
		}
		err = protojson.Unmarshal(data, actual)
		if !assert.NoError(t, err) {
			return
		}
		expected := &AgentConfigurationRequest{
			AgentId:             testhelpers.AgentkKey1.ID,
			AgentConfig:         config,
			AgentConfigCommitId: "any-commit-id",
		}
		matcher.AssertProtoEqual(t, expected, actual)
		w.WriteHeader(http.StatusNoContent)
	})
	err := PostAgentkConfiguration(ctx, c, testhelpers.AgentkKey1, config, "any-commit-id")
	require.NoError(t, err)
}
