package common

import (
	"context"
	"time"

	"k8s.io/apimachinery/pkg/types"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/controllers/appbox/task"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/deploy"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/helm"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/util"
)

// Goldpinger is a task to deploy goldpinger,
// which tests and displays connectivity between nodes in the cluster.
// It is skipped when goldpinger is not configured in the infra template.
type Goldpinger struct {
	*task.BaseTask
}

func NewGoldpinger(ctx *task.Context) *Goldpinger {
	return &Goldpinger{
		BaseTask: &task.BaseTask{Context: ctx},
	}
}

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

func (t *Goldpinger) shouldSkip() bool {
	return t.InfraTmplConfig.Goldpinger.ChartPath == "" ||
		t.APPBox.Annotations[v1alpha1.AnnotationKeyEnableGoldpinger] != "true"
}

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

func (t *Goldpinger) PostCreate(ctx context.Context) deploy.Result {
	if t.shouldSkip() {
		return deploy.Done()
	}
	return deploy.ErrorOrDone(controllers.EnsureDaemonSetReady(ctx, t.Remote, types.NamespacedName{
		Namespace: t.InfraTmplConfig.Goldpinger.GetNamespace(),
		Name:      t.InfraTmplConfig.Goldpinger.GetName(),
	}))
}
