package facade_imp

import (
	"errors"
	"testing"

	"k8s.io/utils/pointer"
)

func TestIsNoopUpdateServerlessChangefeedError(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		err  error
		want bool
	}{
		{
			name: "nil error",
		},
		{
			name: "unchanged config",
			err: errors.New(
				`400-{"error_msg":"[CDC:ErrChangefeedUpdateRefused]changefeed update error: ` +
					`changefeed config is the same with the old one, do nothing"}`,
			),
			want: true,
		},
		{
			name: "other update refused error",
			err:  errors.New(`[CDC:ErrChangefeedUpdateRefused]changefeed cannot be updated in current state`),
		},
		{
			name: "same text without error code",
			err:  errors.New("changefeed config is the same with the old one, do nothing"),
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			if got := isNoopUpdateServerlessChangefeedError(tt.err); got != tt.want {
				t.Fatalf("isNoopUpdateServerlessChangefeedError() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestBuildServerlessHTTPProxyBaseURL(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name         string
		clusterProxy string
		namespace    *string
		service      *string
		expectedURL  string
		expectErr    bool
	}{
		{
			name:         "default namespace and service",
			clusterProxy: "http://cluster-proxy/proxy/namespace/test/cluster/test",
			expectedURL:  "http://cluster-proxy/proxy/namespace/tidb-serverless/cluster/serverless-cluster",
		},
		{
			name:         "override service only",
			clusterProxy: "http://cluster-proxy/proxy/namespace/test/cluster/test",
			service:      pointer.String("serverless-cluster-dm-master"),
			expectedURL:  "http://cluster-proxy/proxy/namespace/tidb-serverless/cluster/serverless-cluster-dm-master",
		},
		{
			name:         "override namespace and service",
			clusterProxy: "http://cluster-proxy/proxy/namespace/test/cluster/test",
			namespace:    pointer.String("custom-namespace"),
			service:      pointer.String("custom-service"),
			expectedURL:  "http://cluster-proxy/proxy/namespace/custom-namespace/cluster/custom-service",
		},
		{
			name:         "invalid cluster proxy url",
			clusterProxy: "http://cluster-proxy",
			expectErr:    true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			got, err := buildServerlessHTTPProxyBaseURL(tt.clusterProxy, tt.namespace, tt.service)
			if tt.expectErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("expected no error, got %v", err)
			}
			if got != tt.expectedURL {
				t.Fatalf("unexpected url: got %s want %s", got, tt.expectedURL)
			}
		})
	}
}
