package task

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/tidbcloud/infra-provider/pkg/namer"
	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestContext_ProviderConfigName(t *testing.T) {
	t.Run("account nil", func(t *testing.T) {
		c := &Context{
			VPC: &v1alpha1.VPC{},
		}
		assert.Equal(t, "", c.ProviderConfigName())
	})
	t.Run("account not nil", func(t *testing.T) {
		c := &Context{
			VPC: &v1alpha1.VPC{
				Spec: v1alpha1.VPCSpec{
					AccountRef: &v1alpha1.AccountReference{
						ProviderConfigName: "test",
					},
				},
			},
		}
		assert.Equal(t, "test", c.ProviderConfigName())
	})
}

func TestContext_InternetName(t *testing.T) {
	t.Run("annotation not empty", func(t *testing.T) {
		c := &Context{
			Internet: &v1alpha1.Internet{
				ObjectMeta: metav1.ObjectMeta{
					Name: "internet-test-1af1a690",
					Annotations: map[string]string{
						v1alpha1.AnnotationKeyOwnCrossplaneNameVPC: "test",
					},
				},
			},
		}
		assert.Equal(t, "test", c.InternetName())
	})
	t.Run("annotation empty", func(t *testing.T) {
		c := &Context{
			Internet: &v1alpha1.Internet{
				ObjectMeta: metav1.ObjectMeta{
					Name: "internet-test-1af1a690",
				},
			},
		}
		assert.Contains(t, c.InternetName(), "internet-test-1af1a690")
	})
}

func TestContext_VPCName(t *testing.T) {
	t.Run("annotation not empty", func(t *testing.T) {
		c := &Context{
			Internet: &v1alpha1.Internet{
				ObjectMeta: metav1.ObjectMeta{
					Name: "internet-test-1af1a690",
					Annotations: map[string]string{
						v1alpha1.AnnotationKeyOwnCrossplaneNameVPC: "test",
					},
				},
			},
		}
		assert.Equal(t, "test", c.VPCName())
	})
	t.Run("get from vpc status", func(t *testing.T) {
		c := &Context{
			Internet: &v1alpha1.Internet{
				ObjectMeta: metav1.ObjectMeta{
					Name: "internet-test-1af1a690",
				},
			},
			VPC: &v1alpha1.VPC{
				ObjectMeta: metav1.ObjectMeta{
					Name: "vpc-test-1af1a690",
				},
				Status: v1alpha1.VPCStatus{
					VPC: v1alpha1.VPCRes{
						Name: "vpc-test-generate",
					},
				},
			},
		}
		assert.Equal(t, "vpc-test-generate", c.VPCName())
	})
	t.Run("generate unique identifier", func(t *testing.T) {
		c := &Context{
			Internet: &v1alpha1.Internet{
				ObjectMeta: metav1.ObjectMeta{
					Name: "internet-test-1af1a690",
				},
			},
			VPC: &v1alpha1.VPC{
				ObjectMeta: metav1.ObjectMeta{
					Name: "vpc-test-1af1a690",
				},
			},
		}
		assert.Contains(t, c.VPCName(), namer.UniqueIdentifier(c.VPC.ObjectMeta))
	})
}
