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/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/config"
	"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"
)

type TiFlowOperator struct {
	*task.BaseTask
	config *tiflowOperatorConfig
}

type tiflowOperatorConfig struct {
	config.InfraComponentConfig
	overwriteImageTag string
}

func (c *tiflowOperatorConfig) ToHelmValues() map[string]interface{} {
	values := c.InfraComponentConfig.ToHelmValues()
	if c.overwriteImageTag != "" {
		image := values["image"]
		image.(map[string]interface{})["tag"] = c.overwriteImageTag
	}
	return values
}

func NewTiFlowOperator(ctx *task.Context) *TiFlowOperator {
	return &TiFlowOperator{
		BaseTask: &task.BaseTask{Context: ctx},
		config: &tiflowOperatorConfig{
			InfraComponentConfig: ctx.DPTmplConfig.TiFlowOperator,
		},
	}
}

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

func (t *TiFlowOperator) Create(ctx context.Context) deploy.Result {
	t.BeginAt = util.Pointer(time.Now())
	if tag := t.APPBox.Annotations[v1alpha1.AnnotationKeyOwnImageTagTiFlowOperator]; tag != "" {
		t.config.overwriteImageTag = tag
	}
	return deploy.ErrorOrDone(helm.Apply(ctx, t.Remote, t.config))
}

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