package gardener

import (
	"context"
	"testing"

	"github.com/google/go-cmp/cmp"
	. "github.com/onsi/gomega"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/utils/pointer"
	"sigs.k8s.io/controller-runtime/pkg/client/fake"

	"github.com/tidbcloud/infra-api/pkg/consts"
)

func TestDeployLocalProxy(t *testing.T) {
	g := NewGomegaWithT(t)
	client := fake.NewClientBuilder().Build()
	ctx := context.Background()

	_, err := deployLocalProxy(ctx, client, "cluster-proxy", "us-west-2", "aws", []string{"0.0.0.0/0"}, "audient", "domain")
	g.Expect(err).Should(Succeed())

	// just check duplicate call will not cause error
	_, err = deployLocalProxy(ctx, client, "cluster-proxy", "us-west-2", "aws", []string{"0.0.0.0/0"}, "audient", "domain")
	g.Expect(err).Should(Succeed())

	// check deployment
	labels := map[string]string{
		"app": localProxyName,
	}

	deploy := &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      localProxyName,
			Namespace: consts.LocalOperatorNamespace,
		},
		Spec: appsv1.DeploymentSpec{
			Replicas: pointer.Int32Ptr(2),
			Selector: &metav1.LabelSelector{
				MatchLabels: labels,
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labels,
				},
				Spec: corev1.PodSpec{
					ServiceAccountName: localProxyName,
					Volumes: []corev1.Volume{
						{
							Name: "tls-certs",
							VolumeSource: corev1.VolumeSource{
								Secret: &corev1.SecretVolumeSource{
									SecretName:  "proxy-certificate-secret",
									DefaultMode: pointer.Int32(0422),
								},
							},
						},
					},
					Affinity: &corev1.Affinity{
						PodAntiAffinity: &corev1.PodAntiAffinity{
							PreferredDuringSchedulingIgnoredDuringExecution: []corev1.WeightedPodAffinityTerm{
								{
									Weight: 100,
									PodAffinityTerm: corev1.PodAffinityTerm{
										LabelSelector: &metav1.LabelSelector{
											MatchExpressions: []metav1.LabelSelectorRequirement{
												{
													Key:      "app",
													Operator: "In",
													Values:   []string{localProxyName},
												},
											},
										},
										TopologyKey: "kubernetes.io/hostname",
									},
								},
							},
						},
					},
					Containers: []corev1.Container{
						{
							Name:  "proxy",
							Image: "cluster-proxy",
							Command: []string{
								"/proxy",
								"--port", "443",
								"--tls-dir", "/proxy-tls",
								"--gotty-image", "gcr.io/pingcap-public/dbaas/gotty:20211103",
								"--gotty-cmd", "/gotty -w --max-connection 1 --timeout 60 --reconnect /usql --password",
							},
							Env: []corev1.EnvVar{
								{
									Name:  "AUTH0-AUDIENCE",
									Value: "audient",
								},
								{
									Name:  "AUTH0-DOMAIN",
									Value: "domain",
								},
							},
							Resources: corev1.ResourceRequirements{
								Limits: corev1.ResourceList{
									corev1.ResourceCPU:    resource.MustParse("100m"),
									corev1.ResourceMemory: resource.MustParse("256Mi"),
								},
								Requests: corev1.ResourceList{
									corev1.ResourceCPU:    resource.MustParse("20m"),
									corev1.ResourceMemory: resource.MustParse("80Mi"),
								},
							},
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "tls-certs",
									MountPath: "/proxy-tls",
								},
							},
						},
					},
				},
			},
		}}

	getDeploy := new(appsv1.Deployment)
	err = client.Get(ctx, types.NamespacedName{Namespace: consts.LocalOperatorNamespace, Name: localProxyName}, getDeploy)
	g.Expect(err).Should(Succeed())
	diff := cmp.Diff(deploy.Spec, getDeploy.Spec)
	if diff != "" {
		t.Errorf("unexpected (-want, +got): %s", diff)
	}

	// check service
	svc := &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      localProxyName,
			Namespace: consts.LocalOperatorNamespace,
		},
		Spec: corev1.ServiceSpec{
			Ports: []corev1.ServicePort{{
				Port:       443,
				TargetPort: intstr.FromInt(443),
				Protocol:   corev1.ProtocolTCP,
			}},
			Selector:                 labels,
			Type:                     corev1.ServiceTypeLoadBalancer,
			LoadBalancerSourceRanges: []string{"0.0.0.0/0"},
		},
	}

	getSvc := new(corev1.Service)
	err = client.Get(ctx, types.NamespacedName{Namespace: consts.LocalOperatorNamespace, Name: localProxyName}, getSvc)
	g.Expect(err).Should(Succeed())
	diff = cmp.Diff(svc.Spec, getSvc.Spec)
	if diff != "" {
		t.Errorf("unexpected (-want, +got): %s", diff)
	}
}
