package config

import (
	"io"
	"log"
	"os"
	"path/filepath"
	"time"

	helm_client "github.com/mittwald/go-helm-client"
)

type RepoSettings struct {
	Name     string
	URL      string
	Username string
	Password string
}

type ChartSettings struct {
	ReleaseName     string
	ChartRef        string
	ChartVersion    string
	Namespace       string
	CreateNamespace bool
	Atomic          bool
	Timeout         time.Duration
	ValuesYaml      string
}

func GetHelmClient(namespace string) helm_client.Client {
	config := GetConfig()
	file, err := os.Open(filepath.Join(config.WorkDir, config.KubeconfigFile))
	if err != nil {
		log.Fatalf("failed to open file: %s", err)
	}
	defer file.Close()
	kubeconfig, err := io.ReadAll(file)
	if err != nil {
		log.Fatalf("failed to read file: %s", err)
	}
	opts := &helm_client.KubeConfClientOptions{
		Options: &helm_client.Options{
			Namespace:        namespace,
			RepositoryCache:  "/tmp/.helmcache",
			RepositoryConfig: "/tmp/.helmrepo",
			Debug:            true,
			Linting:          true, // Change this to false if you don't want linting.
			DebugLog: func(format string, v ...interface{}) {
				// Change this to your own logger. Default is 'log.Printf(format, v...)'.
			},
		},
		KubeContext: "",
		KubeConfig:  kubeconfig,
	}
	client, err := helm_client.NewClientFromKubeConf(opts)
	if err != nil {
		log.Fatalf("error while creating helm client: %s", err)
	}

	return client
}
