package agentk

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/mock_k8s"
	"go.uber.org/mock/gomock"
	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func TestModule_FailedToListFluxResources(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockMapper := mock_k8s.NewMockResettableRESTMapper(ctrl)

	// setup mock expectations
	mockMapper.EXPECT().ResourcesFor(gomock.Any()).Return(nil, &meta.NoResourceMatchError{})

	// WHEN
	ok, err := checkResourceExists(mockMapper, testSupportedCRD)

	// THEN
	assert.NoError(t, err)
	assert.False(t, ok)
}

func TestModule_SuccessfullyListedClusterFluxResources(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockMapper := mock_k8s.NewMockResettableRESTMapper(ctrl)

	// setup mock expectations
	mockMapper.EXPECT().ResourcesFor(gomock.Any()).Return([]schema.GroupVersionResource{requiredFluxCRDs[0]}, nil)

	// WHEN
	ok, err := checkResourceExists(mockMapper, testSupportedCRD)

	// THEN
	require.NoError(t, err)
	assert.True(t, ok)
}

func TestModule_SuccessfullyListedNamespaceFluxResources(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockMapper := mock_k8s.NewMockResettableRESTMapper(ctrl)

	// setup mock expectations
	mockMapper.EXPECT().ResourcesFor(gomock.Any()).Return([]schema.GroupVersionResource{requiredFluxCRDs[0]}, nil)
	// WHEN
	ok, err := checkResourceExists(mockMapper, testSupportedCRD)

	// THEN
	require.NoError(t, err)
	assert.True(t, ok)
}
