// Code generated by lingon. EDIT AS MUCH AS YOU LIKE.

package team

import (
	"context"
	"errors"
	"os"
	"os/exec"

	kube "github.com/golingon/lingon/pkg/kube"
	networkingv1beta1 "istio.io/client-go/pkg/apis/networking/v1beta1"

	secretsstorecsidriverapisv1 "sigs.k8s.io/secrets-store-csi-driver/apis/v1"
)

// validate the struct implements the interface
var _ kube.Exporter = (*Team)(nil)

// Team contains kubernetes manifests
type Team struct {
	kube.App

	TeamGraphMicrosoftServiceEntry        *networkingv1beta1.ServiceEntry
	TeamOnboardingAuthSecretProviderClass *secretsstorecsidriverapisv1.SecretProviderClass
}

// New creates a new Team
func New() *Team {
	return &Team{
		TeamGraphMicrosoftServiceEntry:        TeamGraphMicrosoftServiceEntry,
		TeamOnboardingAuthSecretProviderClass: TeamOnboardingAuthSecretProviderClass,
	}
}

// Apply applies the kubernetes objects to the cluster
func (a *Team) Apply(ctx context.Context) error {
	return Apply(ctx, a)
}

// Export exports the kubernetes objects to YAML files in the given directory
func (a *Team) Export(dir string) error {
	return kube.Export(a, kube.WithExportOutputDirectory(dir))
}

// Apply applies the kubernetes objects contained in Exporter to the cluster
func Apply(ctx context.Context, km kube.Exporter) error {
	cmd := exec.CommandContext(ctx, "kubectl", "apply", "-f", "-")
	cmd.Env = os.Environ()        // inherit environment in case we need to use kubectl from a container
	stdin, err := cmd.StdinPipe() // pipe to pass data to kubectl
	if err != nil {
		return err
	}

	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	go func() {
		defer func() {
			err = errors.Join(err, stdin.Close())
		}()
		if errEW := kube.Export(km, kube.WithExportWriter(stdin), kube.WithExportAsSingleFile("stdin")); errEW != nil {
			err = errors.Join(err, errEW)
		}
	}()

	if errS := cmd.Start(); errS != nil {
		return errors.Join(err, errS)
	}

	// waits for the command to exit and waits for any copying
	// to stdin or copying from stdout or stderr to complete
	return errors.Join(err, cmd.Wait())
}

// P converts T to *T, useful for basic types
func P[T any](t T) *T {
	return &t
}
