package gke

import (
	"fmt"

	"github.com/pingcap/tiflow-operator/api/v1alpha1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"

	"github.com/tidbcloud/eks-provider/controllers/tiflow/task"
	"github.com/tidbcloud/infra-provider/pkg/config"
)

const (
	rdsSecretVolumeName string = "tiflow-rds-secret"
)

func AddCloudSQLProxyToComponentSpec(config *config.RootConfig, componentSpec *v1alpha1.ComponentSpec) error {
	// we will use a special database user like 'dataflow'@'cloudsqlproxy~%' without password to connect to Cloud SQL Proxy
	// see https://cloud.google.com/sql/docs/mysql/sql-proxy#user
	rdsPort := fmt.Sprintf("--port=%d", config.TiflowCluster.Master.ShareDb.Port)
	rdsServiceName := config.TiflowCluster.Master.ShareDb.ServiceName

	componentSpec.AdditionalVolumes = []corev1.Volume{
		{
			Name: rdsSecretVolumeName,
			VolumeSource: corev1.VolumeSource{
				Secret: &corev1.SecretVolumeSource{
					SecretName: task.RDSSecretName,
				},
			},
		},
	}

	nonRoot := true
	// ref to: https://cloud.google.com/sql/docs/mysql/connect-kubernetes-engine
	componentSpec.AdditionalContainers = []corev1.Container{
		{
			Name:  "cloud-sql-proxy",
			Image: config.TiflowCluster.Master.ShareDb.ProxyImage,
			Args: []string{
				// Enable structured logging with LogEntry format:
				"--structured-logs",
				// `credentials_json` is the file name projected by rds secret volume
				"--credentials-file=/secrets/credentials_json",
				rdsPort,
				rdsServiceName,
			},
			SecurityContext: &corev1.SecurityContext{
				RunAsNonRoot: &nonRoot,
			},
			Resources: corev1.ResourceRequirements{
				Requests: corev1.ResourceList{
					corev1.ResourceMemory: resource.MustParse("100Mi"),
					corev1.ResourceCPU:    resource.MustParse("100m"),
				},
			},
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      rdsSecretVolumeName,
					ReadOnly:  true,
					MountPath: "/secrets/",
				},
			},
		},
	}

	return nil
}
