package agentk

import (
	"context"
	"crypto/hmac"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"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_stdlib"
	"go.uber.org/mock/gomock"
)

func TestReconcileTrigger_WithKubeProxyApiUrl(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	dummyKubeAPIURL := &url.URL{Scheme: "http", Host: "localhost", Path: "kubeapi"}
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)
	cfgURL := "/api/v1/namespaces/flux-system/services/http:webhook-receiver:80/proxy"
	expectedURL := &url.URL{Scheme: "http", Host: "localhost", Path: "/kubeapi/api/v1/namespaces/flux-system/services/http:webhook-receiver:80/proxy/some/webhook/path"}

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		return r.URL.String() == expectedURL.String()
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger(cfgURL, dummyKubeAPIURL, mockRoundTripper, nil)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

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

func TestReconcileTrigger_WithDefaultServiceUrl(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)
	expectedURL := &url.URL{Scheme: "http", Host: "webhook-receiver.flux-system.svc.cluster.local", Path: "/some/webhook/path"}

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		return r.URL.String() == expectedURL.String()
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger(defaultServiceAPIBaseURL, nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

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

func TestReconcileTrigger_WithCustomServiceUrl(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)
	expectedURL := &url.URL{Scheme: "https", Host: "localhost", Path: "/some/webhook/path"}

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		return r.URL.String() == expectedURL.String()
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger("https://localhost", nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

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

func TestReconcileTrigger_Failure(t *testing.T) {
	// GIVEN
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(gomock.Any()).Return(&http.Response{StatusCode: http.StatusUnauthorized, Status: "401 Unauthorized", Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger("https://localhost", nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

	// THEN
	assert.ErrorContains(t, err, "trigger to \"https://localhost/some/webhook/path\" returned status \"401 Unauthorized\"")
}

func TestReconcileTrigger_HMACBodyAndHeaderArePresent(t *testing.T) {
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		return strings.Contains(r.Header["X-Signature"][0], "sha256=") && r.Body != nil
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger(defaultServiceAPIBaseURL, nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

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

func TestReconcileTrigger_HMACSignatureIsSHA256(t *testing.T) {
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		sha256Regex := regexp.MustCompile(`^[a-f0-9]{64}$`)
		hashType, hashValue := func() (string, string) {
			x := strings.Split(r.Header["X-Signature"][0], "=")
			return x[0], x[1]
		}()
		return sha256Regex.MatchString(hashValue) && hashType == "sha256"
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger(defaultServiceAPIBaseURL, nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", []byte("secretValue"))

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

func TestReconcileTrigger_CompareHMACSignature(t *testing.T) {
	ctrl := gomock.NewController(t)
	mockRoundTripper := mock_stdlib.NewMockRoundTripper(ctrl)
	key := []byte("secretValue")

	// setup mock expectations
	mockRoundTripper.EXPECT().RoundTrip(matcher.DoMatch(func(r *http.Request) bool {
		defer r.Body.Close()
		bodyBytes, err := io.ReadAll(r.Body)
		if err != nil {
			return false
		}
		bodyString := string(bodyBytes)
		_, hashValue := func() (string, string) {
			x := strings.Split(r.Header["X-Signature"][0], "=")
			return x[0], x[1]
		}()
		return hmac.Equal([]byte(generateHMACsignature(bodyString, key)), []byte(hashValue))
	})).Return(&http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil).Times(1)

	// WHEN
	rt, err := newGitRepositoryReconcileTrigger(defaultServiceAPIBaseURL, nil, nil, mockRoundTripper)
	require.NoError(t, err)

	err = rt.reconcile(context.Background(), "/some/webhook/path", key)

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