/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package templates

import (
	"path/filepath"

	"sigs.k8s.io/kubebuilder/v4/pkg/machinery"
	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/internal/common"
	"sigs.k8s.io/kubebuilder/v4/pkg/plugins/optional/helm/v2alpha/scaffolds/internal/extractor"
)

var _ machinery.Template = &HelmChart{}

// HelmChart scaffolds a file that defines the Helm chart structure
type HelmChart struct {
	machinery.TemplateMixin
	machinery.ProjectNameMixin

	// OutputDir specifies the output directory for the chart
	OutputDir string
	// ChartMetadata contains metadata extracted from kustomize resources (name, version)
	ChartMetadata extractor.ChartMetadata
}

// SetTemplateDefaults implements machinery.Template
func (f *HelmChart) SetTemplateDefaults() error {
	if f.Path == "" {
		outputDir := f.OutputDir
		if outputDir == "" {
			outputDir = common.DefaultOutputDir
		}
		f.Path = filepath.Join(outputDir, "chart", "Chart.yaml")
	}

	f.TemplateBody = helmChartTemplate

	// Chart.yaml is never overwritten as it contains user-managed version info
	f.IfExistsAction = machinery.SkipFile

	return nil
}

const helmChartTemplate = `apiVersion: v2
name: {{ if .ChartMetadata.ChartName }}{{ .ChartMetadata.ChartName }}{{ else }}{{ .ProjectName }}{{ end }}
description: A Helm chart to distribute {{ .ProjectName }}
type: application

version: 0.1.0
appVersion: "{{ if .ChartMetadata.ManagerVersion }}{{ .ChartMetadata.ManagerVersion }}{{ else }}0.1.0{{ end }}"

keywords:
  - kubernetes
  - operator

annotations:
  kubebuilder.io/generated-by: kubebuilder
`
