package common

import (
	"context"
	"time"

	"github.com/tidbcloud/infra-provider/pkg/deploy"
	"github.com/tidbcloud/infra-provider/pkg/helm"
	"github.com/tidbcloud/infra-provider/pkg/util"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers/appbox/task"
	"k8s.io/apimachinery/pkg/types"
)

// KubeStateMetrics is a task to deploy kube-state-metrics (KSM),
// which is a simple service that listens to the Kubernetes API server
// and generates metrics about the state of the objects.
type KubeStateMetrics struct {
	*task.BaseTask
}

func NewKubeStateMetrics(ctx *task.Context) *KubeStateMetrics {
	return &KubeStateMetrics{
		BaseTask: &task.BaseTask{Context: ctx},
	}
}

func (t *KubeStateMetrics) Name() string {
	return "KubeStateMetrics"
}

func (t *KubeStateMetrics) Create(ctx context.Context) deploy.Result {
	t.BeginAt = util.Pointer(time.Now())
	return deploy.ErrorOrDone(helm.Apply(ctx, t.Remote, t.InfraTmplConfig.KubeStateMetrics))
}

func (t *KubeStateMetrics) PostCreate(ctx context.Context) (res deploy.Result) {
	return deploy.ErrorOrDone(controllers.EnsureChartDeploymentReady(ctx, t.Remote, types.NamespacedName{
		Namespace: t.InfraTmplConfig.KubeStateMetrics.GetNamespace(),
		Name:      t.InfraTmplConfig.KubeStateMetrics.GetName(),
	}))
}
