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/api"
	"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"
	"google.golang.org/protobuf/encoding/protojson"
)

func TestAuthorizeProxyUser(t *testing.T) {
	const (
		configProjectID int64      = 21
		accessType      AccessType = SessionCookieAccessType
		accessKey       string     = "damndeliciouscookie"
		csrfToken       string     = "token"
	)
	agentKey := api.AgentKey{ID: 42, Type: api.AgentTypeKubernetes}
	ctx, _ := testhelpers.CtxWithSpanContext(t)
	response := &AuthorizeProxyUserAPIResponse{
		Agent: &AuthorizedAgentForUser{
			Id:            agentKey.ID,
			ConfigProject: &ConfigProject{Id: configProjectID},
		},
		User: &User{
			Id:       1234,
			Username: "any-user",
		},
		AccessAs: &AccessAsProxyAuthorization{
			AccessAs: &AccessAsProxyAuthorization_User{
				User: &AccessAsUserAuthorization{
					Projects: []*ProjectAccessCF{
						{
							Id:    configProjectID,
							Roles: []string{"Developer"},
						},
					},
				},
			},
		},
	}
	gitLabClient := mock_gitlab.SetupClient(t, "", AuthorizeProxyUserAPIPath, func(w http.ResponseWriter, r *http.Request) {
		testhelpers.AssertRequestMethod(t, r, http.MethodPost)

		data, err := io.ReadAll(r.Body)
		if !assert.NoError(t, err) {
			return
		}
		actual := &AuthorizeProxyUserAPIRequest{}
		err = protojson.Unmarshal(data, actual)
		if !assert.NoError(t, err) {
			return
		}
		expected := &AuthorizeProxyUserAPIRequest{
			AgentId:    agentKey.ID,
			AccessType: string(accessType),
			AccessKey:  accessKey,
			CsrfToken:  csrfToken,
		}

		matcher.AssertProtoEqual(t, expected, actual)
		testhelpers.RespondWithJSON(t, w, response)
	})

	auth, err := AuthorizeProxyUser(ctx, gitLabClient, agentKey, accessType, accessKey, csrfToken)
	require.NoError(t, err)

	assert.Equal(t, response.Agent.Id, auth.Response.Agent.Id)
}
