package agent

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

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

func TestSecurityPoliciesWorker(t *testing.T) {
	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{
				agentId: testhelpers.AgentId,
				containerScanningConfig: &agentcfg.ContainerScanningCF{
					Cadence: "0 2 * * *",
					VulnerabilityReport: &agentcfg.VulnerabilityReport{
						Namespaces: []string{"ns1", "ns2"},
					},
				},
			},
		},
		{
			description: "worker sends update when a policy is not present",
			status:      http.StatusOK,
			response: &getSecurityPoliciesResponse{
				Policies: []*SecurityPolicyConfiguration{},
			},
			expected: configurationToUpdateData{
				agentId:                 testhelpers.AgentId,
				containerScanningConfig: nil,
			},
		},
		{
			description: "works sends update when status is 404",
			status:      http.StatusNotFound,
			response:    nil,
			expected: configurationToUpdateData{
				agentId:                 testhelpers.AgentId,
				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().
				GetAgentId(ctx).
				MinTimes(1).
				Return(testhelpers.AgentId, nil)

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

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

			policiesWorker.Run(ctx)
		})
	}
}
