package additional

import (
	"kube-forge/internal/config"
	"kube-forge/internal/helm_client"
	"kube-forge/internal/templates"
	"time"

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

var HELM_REPOS = []config.RepoSettings{
	{
		Name: "kube-forge",
		URL:  "https://git.kvazaric.ru/api/v4/projects/41/packages/helm/stable",
	},
}

func getCertManagerSpec() go_helm_client.ChartSpec {
	appConfig := config.GetConfig()
	return go_helm_client.ChartSpec{
		ReleaseName:     "cert-manager",
		ChartName:       appConfig.Modules.Additional.CertManager.ChartRef,
		Version:         appConfig.Modules.Additional.CertManager.ChartVersion,
		Namespace:       appConfig.Modules.Additional.CertManager.Namespace,
		CreateNamespace: true,
		Atomic:          true,
		Timeout:         time.Second * 600,
		ValuesYaml:      templates.GetHelmValuesByTemplate("templates/helm-apps/releases/additional-modules/cert-manager.yml.tmpl"),
	}
}

func getIngressNginxSpec() go_helm_client.ChartSpec {
	appConfig := config.GetConfig()
	return go_helm_client.ChartSpec{
		ReleaseName:     "ingress-nginx",
		ChartName:       appConfig.Modules.Additional.Ingress.ChartRef,
		Version:         appConfig.Modules.Additional.Ingress.ChartVersion,
		Namespace:       appConfig.Modules.Additional.Ingress.Namespace,
		CreateNamespace: true,
		Atomic:          true,
		Timeout:         time.Second * 600,
		ValuesYaml:      templates.GetHelmValuesByTemplate("templates/helm-apps/releases/additional-modules/ingress-nginx.yml.tmpl"),
	}
}

func getDockerSecretsGeneratorSpec() go_helm_client.ChartSpec {
	appConfig := config.GetConfig()
	return go_helm_client.ChartSpec{
		ReleaseName:     "docker-secrets-generator",
		ChartName:       appConfig.Modules.Additional.DockerSecrets.ChartRef,
		Version:         appConfig.Modules.Additional.DockerSecrets.ChartVersion,
		Namespace:       appConfig.Modules.Additional.DockerSecrets.Namespace,
		CreateNamespace: true,
		Atomic:          true,
		Timeout:         time.Second * 600,
		ValuesYaml:      templates.GetHelmValuesByTemplate("templates/helm-apps/releases/additional-modules/docker-secrets-generator.yml.tmpl"),
	}
}

func ApplyCharts() {
	appConfig := config.GetConfig()
	helm_client.AddHelmRepos("kube-system", HELM_REPOS)
	if appConfig.Modules.Additional.CertManager.Enabled {
		helm_client.InstallChart(getCertManagerSpec())
	} else {
		helm_client.DeleteChart(getCertManagerSpec())
	}
	if appConfig.Modules.Additional.Ingress.Enabled && appConfig.Modules.Additional.Ingress.Type == "nginx" {
		helm_client.InstallChart(getIngressNginxSpec())
	} else {
		helm_client.DeleteChart(getIngressNginxSpec())
	}
	if appConfig.Modules.Additional.DockerSecrets.Repositories != nil {
		helm_client.InstallChart(getDockerSecretsGeneratorSpec())
	} else {
		helm_client.DeleteChart(getDockerSecretsGeneratorSpec())
	}
}
