package commonazure

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	azurenetworkv1beta2 "github.com/upbound/provider-azure/apis/network/v1beta2"
	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 TestPrivateLinkIPTask_Create(t *testing.T) {
	tests := []struct {
		name           string
		clusterName    string
		setupResources func(client.Client)
		mutateAgent    func(client.Object)
		verify         func(*testing.T, client.Object)
		errMsg         string
	}{
		{
			name:        "empty cluster name",
			clusterName: "",
			errMsg:      "kubernetes cluster name is empty",
		},
		{
			name:        "no PE found for cluster",
			clusterName: "cluster-1",
			errMsg:      "no private endpoint found for cluster cluster-1",
		},
		{
			name:        "PE found but no IP",
			clusterName: "cluster-1",
			setupResources: func(c client.Client) {
				ep := &azurenetworkv1beta2.PrivateEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "pe-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
				}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			errMsg: "private endpoint pe-1 has empty private IP",
		},
		{
			name:        "success: PE with IP in CustomDNSConfigs",
			clusterName: "cluster-1",
			setupResources: func(c client.Client) {
				ep := &azurenetworkv1beta2.PrivateEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "pe-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
				}
				ep.Status.AtProvider.CustomDNSConfigs = []azurenetworkv1beta2.CustomDNSConfigsObservation{{
					IPAddresses: []*string{ptr.To("10.0.0.1")},
				}}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, "10.0.0.1", util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "success: PE with IP in PrivateServiceConnection",
			clusterName: "cluster-1",
			setupResources: func(c client.Client) {
				ep := &azurenetworkv1beta2.PrivateEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "pe-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
				}
				ep.Status.AtProvider.PrivateServiceConnection = &azurenetworkv1beta2.PrivateServiceConnectionObservation{
					PrivateIPAddress: ptr.To("10.0.0.2"),
				}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, "10.0.0.2", util.GetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName))
			},
		},
		{
			name:        "no update needed",
			clusterName: "cluster-1",
			mutateAgent: func(obj client.Object) {
				util.SetAnnotation(obj, consts.AnnotationKeyO11yServiceDNSName, "10.0.0.3")
			},
			setupResources: func(c client.Client) {
				ep := &azurenetworkv1beta2.PrivateEndpoint{
					ObjectMeta: metav1.ObjectMeta{
						Name: "pe-1",
						Labels: map[string]string{
							consts.LabelKeyRelatedCluster: "cluster-1",
						},
					},
				}
				ep.Status.AtProvider.CustomDNSConfigs = []azurenetworkv1beta2.CustomDNSConfigsObservation{{
					IPAddresses: []*string{ptr.To("10.0.0.3")},
				}}
				assert.NoError(t, c.Create(context.Background(), ep))
			},
			verify: func(t *testing.T, obj client.Object) {
				assert.Equal(t, "10.0.0.3", 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 := NewPrivateLinkIPTask(ctx, tt.clusterName)
			assert.Equal(t, "PrivateLinkIP", 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, agent)
			}
		})
	}
}
