package commonalicloud

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	aliplv1alpha1 "github.com/crossplane-contrib/provider-upjet-alibabacloud/apis/privatelink/v1alpha1"
	"github.com/stretchr/testify/assert"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/tidbcloud/observability/agent-control-server/pkg/config"
	"github.com/tidbcloud/observability/agent-control-server/pkg/consts"
	"github.com/tidbcloud/observability/agent-control-server/pkg/deploy"
	"github.com/tidbcloud/observability/agent-control-server/pkg/reconciler"
	"github.com/tidbcloud/observability/agent-control-server/pkg/testkits"
	"github.com/tidbcloud/observability/agent-control-server/pkg/util"
)

func TestPrivateLinkNameTask_CreateWithUpbound(t *testing.T) {
	tests := []struct {
		name           string
		clusterName    string
		setupResources func(client.Client)
		mutateAgent    func(client.Object)
		verify         func(t *testing.T, c client.Client, obj client.Object)
		errMsg         string
	}{
		{
			name:        "empty cluster name",
			clusterName: "",
			errMsg:      "kubernetes cluster name is empty",
		},
		{
			name:        "no vpc endpoint found",
			clusterName: "cluster-1",
			errMsg:      "no vpc endpoint found for cluster cluster-1",
		},
		{
			name:        "vpc endpoint has empty domain",
			clusterName: "cluster-1",
			setupResources: func(c client.Client) {
				ep := &aliplv1alpha1.VpcEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "ep-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
					Status: aliplv1alpha1.VpcEndpointStatus{
						AtProvider: aliplv1alpha1.VpcEndpointObservation{EndpointDomain: nil},
					},
				}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			errMsg: "vpc endpoint ep-1 has empty endpoint domain",
		},
		{
			name:        "success update",
			clusterName: "cluster-1",
			setupResources: func(c client.Client) {
				ep := &aliplv1alpha1.VpcEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "ep-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
					Status: aliplv1alpha1.VpcEndpointStatus{
						AtProvider: aliplv1alpha1.VpcEndpointObservation{
							EndpointDomain: ptr.To("ep.domain.com"),
						},
					},
				}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			verify: func(t *testing.T, c client.Client, obj client.Object) {
				assert.Equal(t, "ep.domain.com", util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "success no update needed",
			clusterName: "cluster-1",
			mutateAgent: func(obj client.Object) {
				util.SetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName, "ep.domain.com")
			},
			setupResources: func(c client.Client) {
				ep := &aliplv1alpha1.VpcEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "ep-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
					Status: aliplv1alpha1.VpcEndpointStatus{
						AtProvider: aliplv1alpha1.VpcEndpointObservation{
							EndpointDomain: ptr.To("ep.domain.com"),
						},
					},
				}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			verify: func(t *testing.T, c client.Client, obj client.Object) {
				assert.Equal(t, "ep.domain.com", util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			agent := &corev1.ConfigMap{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-agent",
					Namespace: "default",
				},
			}
			if tt.mutateAgent != nil {
				tt.mutateAgent(agent)
			}

			fakeCli := testkits.BuildClient(agent)
			if tt.setupResources != nil {
				tt.setupResources(fakeCli)
			}

			ctx := &reconciler.Context[*corev1.ConfigMap]{
				Agent:  agent,
				Local:  fakeCli,
				Config: &config.RootConfig{},
			}

			task := NewPrivateLinkNameTask(ctx, tt.clusterName)
			assert.Equal(t, "PrivateLinkName", task.Name())

			res := task.Create(context.Background())
			if tt.errMsg != "" {
				assert.Contains(t, res.Error().Error(), tt.errMsg)
			} else {
				assert.Equal(t, deploy.Done(), res)
			}

			if tt.verify != nil {
				tt.verify(t, fakeCli, agent)
			}
		})
	}
}

func TestPrivateLinkNameTask_CreateWithNativeAPI(t *testing.T) {
	clusterName := "test-cluster"
	endpointID := "ep-xxx"
	endpointDomain := "ep-xxx.epsrv-test.cn-hangzhou.privatelink.aliyuncs.com"

	tests := []struct {
		name        string
		clusterName string
		region      string
		handler     http.HandlerFunc
		mutateAgent func(client.Object)
		verify      func(t *testing.T, obj client.Object)
		errMsg      string
	}{
		{
			name:        "success with active endpoint",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     endpointID,
							"EndpointDomain": endpointDomain,
							"EndpointStatus": "Active",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, endpointDomain, util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "success with available endpoint",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     endpointID,
							"EndpointDomain": endpointDomain,
							"EndpointStatus": "Available",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, endpointDomain, util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "skip pending endpoint and return active one",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     "ep-pending",
							"EndpointDomain": "pending.domain.com",
							"EndpointStatus": "Pending",
						},
						{
							"EndpointId":     endpointID,
							"EndpointDomain": endpointDomain,
							"EndpointStatus": "Active",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, endpointDomain, util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "success no update needed - same domain",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			mutateAgent: func(obj client.Object) {
				util.SetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName, endpointDomain)
			},
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     endpointID,
							"EndpointDomain": endpointDomain,
							"EndpointStatus": "Active",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, endpointDomain, util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "no endpoints found",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []any{},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			errMsg: "no vpc endpoint found for cluster test-cluster",
		},
		{
			name:        "endpoint with empty domain",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     endpointID,
							"EndpointDomain": "",
							"EndpointStatus": "Active",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			errMsg: "vpc endpoint ep-xxx has empty endpoint domain",
		},
		{
			name:        "all endpoints in non-active status",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				resp := map[string]any{
					"Endpoints": []map[string]any{
						{
							"EndpointId":     "ep-1",
							"EndpointDomain": "domain1.com",
							"EndpointStatus": "Pending",
						},
						{
							"EndpointId":     "ep-2",
							"EndpointDomain": "domain2.com",
							"EndpointStatus": "Deleting",
						},
					},
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			errMsg: "no vpc endpoint found for cluster test-cluster",
		},
		{
			name:        "api error",
			clusterName: clusterName,
			region:      "cn-hangzhou",
			handler: func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusInternalServerError)
				resp := map[string]any{
					"Code":      "InternalError",
					"Message":   "internal error",
					"RequestId": "req-123",
				}
				json.NewEncoder(w).Encode(resp)
			},
			errMsg: "failed to find vpc endpoint by cluster tag",
		},
		{
			name:        "empty cluster name",
			clusterName: "",
			region:      "cn-hangzhou",
			errMsg:      "kubernetes cluster name is empty",
		},
		{
			name:        "empty region",
			clusterName: clusterName,
			region:      "",
			errMsg:      "region is not configured",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var serverURL string
			if tt.handler != nil {
				ts := httptest.NewServer(tt.handler)
				defer ts.Close()
				serverURL = ts.Listener.Addr().String()
			}

			agent := &corev1.ConfigMap{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "test-agent",
					Namespace: "default",
				},
			}
			if tt.mutateAgent != nil {
				tt.mutateAgent(agent)
			}

			fakeCli := testkits.BuildClient(agent)

			ctx := &reconciler.Context[*corev1.ConfigMap]{
				Agent:    agent,
				Local:    fakeCli,
				AliCloud: testkits.NewAliCloudClient(serverURL),
				Config: &config.RootConfig{
					Mode: config.ModeServerless,
					O11yConfig: config.ObservabilityInfra{
						Region: tt.region,
					},
				},
			}

			task := NewPrivateLinkNameTask(ctx, tt.clusterName)
			res := task.Create(context.Background())

			if tt.errMsg != "" {
				assert.Contains(t, res.Error().Error(), tt.errMsg)
			} else {
				assert.Equal(t, deploy.Done(), res)
			}

			if tt.verify != nil {
				tt.verify(t, agent)
			}
		})
	}
}
