package k8s

import (
	"encoding/base64"
	"fmt"

	ackv1alpha1 "github.com/crossplane-contrib/provider-upjet-alibabacloud/apis/ack/v1alpha1"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

// BuildACKKubeconfig builds a kubeconfig from the given ACK cluster object.
// If assumeRoleARN is provided, it will be used in the exec command for authentication.
//
// Security Policy: This function requires a valid CA certificate from the ACK cluster.
// Empty or missing certificates will cause the function to fail, ensuring TLS verification
// is always enabled. This prevents man-in-the-middle attacks and ensures secure communication
// with the Kubernetes API server.
func BuildACKKubeconfig(ack *ackv1alpha1.ManagedKubernetes, assumeRoleARN string) (*clientcmdapi.Config, error) {
	// Validate certificate is present (similar to EKS implementation)
	cert, ok := ack.Status.AtProvider.CertificateAuthority["cluster_cert"]
	if !ok || cert == nil || *cert == "" {
		return nil, fmt.Errorf("cluster CA certificate is required but not found or empty")
	}

	// Decode and validate certificate data
	ca, err := base64.StdEncoding.DecodeString(*cert)
	if err != nil {
		return nil, fmt.Errorf("failed to decode ack ca data: %w", err)
	}
	if len(ca) == 0 {
		// Defensive check: should not happen due to empty string check above,
		// but validates the decoded result to ensure certificate data is valid
		return nil, fmt.Errorf("decoded CA certificate is empty")
	}

	// Construct cluster info with validated certificate
	cluster := clientcmdapi.NewCluster()
	cluster.CertificateAuthorityData = ca

	// only support public access
	if server, ok := ack.Status.AtProvider.Connections["api_server_internet"]; !ok || server == nil {
		return nil, fmt.Errorf("no public endpoint found for ack")
	} else {
		cluster.Server = *server
	}

	// construct auth info
	auth := clientcmdapi.NewAuthInfo()
	if ack.Status.AtProvider.ID == nil {
		return nil, fmt.Errorf("no cluster id found")
	}
	clusterId := *ack.Status.AtProvider.ID
	args := []string{
		"credential-plugin",
		"get-token",
		"--cluster-id", clusterId,
		"--api-version", "v1beta1",
		"--log-level", "error",
	}
	if assumeRoleARN != "" {
		args = append(args, []string{"--role-arn", assumeRoleARN}...)
	}
	auth.Exec = &clientcmdapi.ExecConfig{
		APIVersion:      v1execConfigAPIVersionV1beta1,
		InteractiveMode: clientcmdapi.NeverExecInteractiveMode,
		Command:         "ack-ram-tool",
		Args:            args,
	}

	cfgctx := clientcmdapi.NewContext()
	cfgctx.Cluster = ack.Name
	cfgctx.AuthInfo = ack.Name

	cfg := clientcmdapi.NewConfig()
	cfg.Contexts[ack.Name] = cfgctx
	cfg.Clusters[ack.Name] = cluster
	cfg.AuthInfos[ack.Name] = auth
	cfg.CurrentContext = ack.Name

	return cfg, nil
}
