package helm

import (
	"context"
	"log"

	"helm.sh/helm/v3/pkg/action"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/rest"
	"k8s.io/utils/ptr"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// helm used kubeclient, use restconfig for consistency
func GetClient(ctx context.Context, restConfig *rest.Config) (client.Client, error) {
	return client.New(restConfig, client.Options{})
}

func GetHelmConfig(ctx context.Context, restConfig *rest.Config, targetNamespace string) (*action.Configuration, error) {
	configFlags := genericclioptions.NewConfigFlags(false)

	// https://github.com/helm/helm/issues/11047
	// helm client can't use rest.Config directly
	// The Manager is constructed from rest.Config and rest.Config is created from configFlags
	// So here we just reverse the process to construct configFlags from rest.Config
	configFlags.APIServer = &restConfig.Host
	configFlags.Insecure = ptr.To(true)
	// Set the namespace in configFlags for proper context
	configFlags.Namespace = &targetNamespace
	configFlags.WrapConfigFn = func(_ *rest.Config) *rest.Config {
		return restConfig
	}
	var c action.Configuration
	if err := c.Init(
		configFlags,
		targetNamespace, // Use target namespace for both release storage and operations
		"configmap",     // use configmap as the driver
		log.Printf,
	); err != nil {
		return nil, err
	}

	return &c, nil
}
