package api

import (
	"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/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/entity"
)

func TestGetAgentInfo_Agentk(t *testing.T) {
	ctx, traceID := testhelpers.CtxWithSpanContext(t)
	response := &GetAgentkInfoResponse{
		ProjectId: 234,
		AgentId:   testhelpers.AgentkKey1.ID,
		AgentName: "agent-x",
		GitalyInfo: &entity.GitalyInfo{
			Address: "example.com",
			Token:   "123123",
			Features: map[string]string{
				"a": "b",
			},
		},
		GitalyRepository: &entity.GitalyRepository{
			StorageName:                   "234",
			RelativePath:                  "123",
			GitObjectDirectory:            "sfasdf",
			GitAlternateObjectDirectories: []string{"a", "b"},
			GlRepository:                  "254634",
			GlProjectPath:                 "64662",
		},
		DefaultBranch: "main",
	}
	c := mock_gitlab.SetupClient(t, "", AgentkInfoAPIPath, func(w http.ResponseWriter, r *http.Request) {
		testhelpers.AssertGetJSONRequestIsCorrect(t, r, traceID)
		testhelpers.RespondWithJSON(t, w, response)
	})
	agentTokenWithType := api.AgentTokenWithType{
		Token: testhelpers.AgentToken,
		Type:  api.AgentTypeKubernetes,
	}
	a, err := GetAgentInfo(ctx, c, agentTokenWithType)
	require.NoError(t, err)

	agentInfo, ok := a.(*api.AgentkInfo)
	require.True(t, ok)

	assert.Equal(t, response.ProjectId, agentInfo.ProjectID)
	assert.Equal(t, response.AgentId, agentInfo.Key.ID)
	assert.Equal(t, response.AgentName, agentInfo.Name)
	AssertGitalyInfo(t, response.GitalyInfo, agentInfo.GitalyInfo)
	AssertGitalyRepository(t, response.GitalyRepository, agentInfo.Repository)
	assert.Equal(t, response.DefaultBranch, agentInfo.DefaultBranch)
}

func TestGetAgentInfo_Agentw(t *testing.T) {
	ctx, traceID := testhelpers.CtxWithSpanContext(t)
	response := &GetAgentwInfoResponse{
		AgentId: testhelpers.AgentwKey1.ID,
	}
	c := mock_gitlab.SetupClient(t, "", AgentwInfoAPIPath, func(w http.ResponseWriter, r *http.Request) {
		testhelpers.AssertGetJSONRequestIsCorrect(t, r, traceID)
		testhelpers.RespondWithJSON(t, w, response)
	})
	agentTokenWithType := api.AgentTokenWithType{
		Token: testhelpers.AgentToken,
		Type:  api.AgentTypeWorkspace,
	}
	a, err := GetAgentInfo(ctx, c, agentTokenWithType)
	require.NoError(t, err)

	agentInfo, ok := a.(*api.AgentwInfo)
	require.True(t, ok)

	assert.Equal(t, response.AgentId, agentInfo.Key.ID)
}
