package agent

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/mock_modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testhelpers"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/agentcfg"
	"go.uber.org/mock/gomock"
)

func TestSecurityPoliciesWorker(t *testing.T) {

	expectedConfig := &agentcfg.ContainerScanningCF{
		Cadence: "0 2 * * *",
		VulnerabilityReport: &agentcfg.VulnerabilityReport{
			Namespaces: []string{"ns1", "ns2"},
		},
	}
	require.NoError(t, DefaultAndValidateCsConfiguration(expectedConfig))

	testCases := []struct {
		description string
		status      int32
		response    *getSecurityPoliciesResponse
		expected    configurationToUpdateData
	}{
		{
			description: "worker sends update when a policy is present",
			status:      http.StatusOK,
			response: &getSecurityPoliciesResponse{
				Policies: []*SecurityPolicyConfiguration{
					{
						Cadence:    "0 2 * * *",
						Namespaces: []string{"ns1", "ns2"},
						UpdatedAt:  time.Now(),
					},
				},
			},
			expected: configurationToUpdateData{
				agentKey:                testhelpers.AgentkKey1,
				containerScanningConfig: expectedConfig,
			},
		},
		{
			description: "worker sends update when a policy is not present",
			status:      http.StatusOK,
			response: &getSecurityPoliciesResponse{
				Policies: []*SecurityPolicyConfiguration{},
			},
			expected: configurationToUpdateData{
				agentKey:                testhelpers.AgentkKey1,
				containerScanningConfig: nil,
			},
		},
		{
			description: "works sends update when status is 404",
			status:      http.StatusNotFound,
			response:    nil,
			expected: configurationToUpdateData{
				agentKey:                testhelpers.AgentkKey1,
				containerScanningConfig: nil,
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.description, func(t *testing.T) {
			ctrl := gomock.NewController(t)
			api := mock_modagent.NewMockAPI(ctrl)
			updater := make(chan configurationToUpdateData)

			ctx, cancel := context.WithCancel(context.Background())

			api.EXPECT().
				MakeGitLabRequest(
					ctx,
					"/policies_configuration",
					gomock.Any(),
				).MinTimes(1).
				DoAndReturn(func(ctx context.Context, path string, opts ...modagent.GitLabRequestOption) (*modagent.GitLabResponse, error) {
					var body []byte
					if tc.response != nil {
						var err error
						body, err = json.Marshal(tc.response)
						require.NoError(t, err)
					}

					return &modagent.GitLabResponse{
						StatusCode: tc.status,
						Body:       io.NopCloser(bytes.NewReader(body)),
					}, nil
				})

			api.EXPECT().
				GetAgentKey(ctx).
				MinTimes(1).
				Return(testhelpers.AgentkKey1, nil)

			policiesWorker := &securityPoliciesWorker{
				api:     api,
				updater: updater,
			}

			go func() {
				data := <-updater
				assert.Equal(t, tc.expected, data)
				cancel()
			}()

			policiesWorker.Run(ctx)
		})
	}
}
