package lightning

import (
	"fmt"
	"net"

	lnconfig "github.com/pingcap/tidb/pkg/lightning/config"
	"github.com/tidbcloud/dataflow-service/pkg/agent/tidbcloud"
)

const (
	defaultPDPortStr = "2379"
)

func AdjustSecFilesInConfig(theConfig *lnconfig.Config, secFiles *tidbcloud.SecurityConfig) {
	if secFiles == nil {
		return
	}
	theConfig.Security = lnconfig.Security{
		CAPath:   secFiles.CACert,
		CertPath: secFiles.TLSCert,
		KeyPath:  secFiles.TLSKey,
	}
}

func AdjustTiDBHostNameInConfig(theConfig *lnconfig.Config, clusterNamePrefix string, clusterNamespace string) {
	// For dev-tier clusters, the generated config's hostname is actually a gateway
	// It can be accessed through the dataflow agent
	// So no need to change the host name and PD host name
	if len(clusterNamePrefix) == 0 && len(clusterNamespace) == 0 {
		return
	}
	theConfig.TiDB.Host = fmt.Sprintf("%s-tidb.%s.svc",
		clusterNamePrefix, clusterNamespace,
	)

	var thePDPortStr string
	_, thePDPortStr, _ = net.SplitHostPort(theConfig.TiDB.PdAddr)
	if len(thePDPortStr) <= 0 {
		thePDPortStr = defaultPDPortStr
	}
	theConfig.TiDB.PdAddr = fmt.Sprintf("%s-pd.%s.svc:%s",
		clusterNamePrefix,
		clusterNamespace,
		thePDPortStr,
	)
}

func AdjustSourceDir(theConfig *lnconfig.Config, credentialsFile string) {
	theConfig.Mydumper.SourceDir = fmt.Sprintf("%s?credentials-file=%s", theConfig.Mydumper.SourceDir, credentialsFile)
}
