package mastermgr

import (
	"context"

	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

	"github.com/tidbcloud/eks-provider/controllers/tiflow/task"
	"github.com/tidbcloud/infra-provider/pkg/deploy"
	"github.com/tidbcloud/infra-provider/pkg/util"
)

// Guardian adds and removes the finalizer of the Cluster.
type Guardian struct {
	*BaseTask
}

func NewGuardian(ctx *Context) *Guardian {
	return &Guardian{BaseTask: &BaseTask{Context: ctx}}
}

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

func (t *Guardian) Create(ctx context.Context) deploy.Result {
	// prevent reconciling objects from different regions
	if t.Network.Spec.Region != t.Config.Network.Region {
		return deploy.Panic(nil)
	}
	// ignore resource that doesn't belong to this region
	if !util.ContainsRegionLabel(t.TiflowClusterMasterManager) {
		if ok, err := util.CheckNetworkRegion(t.Config.Network.Region, t.Network); err != nil {
			return deploy.Panic(err)
		} else if !ok {
			return deploy.Panic(nil)
		}
		// ensure the object contains the region label
		if !util.EnsureRegion(t.TiflowClusterMasterManager, t.Network.Spec.Region) {
			return deploy.Panic(nil).WithRequeuAfter(0)
		}
	}
	if !controllerutil.ContainsFinalizer(t.TiflowClusterMasterManager, task.Finalizer) {
		controllerutil.AddFinalizer(t.TiflowClusterMasterManager, task.Finalizer)
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeuAfter(0)
	}

	return deploy.Done()
}
