package eks

import (
	"context"
	"fmt"

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

	"github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/eks-provider/controllers/dm/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 {
	*task.BaseTask
}

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

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

func (t *Guardian) Create(ctx context.Context) deploy.Result {
	// ignore resource that doesn't belong to this region
	if !util.ContainsRegionLabel(t.DMJob) {
		// ensure the object contains the region label
		if !util.EnsureRegion(t.DMJob, t.GetRegion()) {
			return deploy.Panic(nil).WithRequeuAfter(0)
		}
	}

	if !controllerutil.ContainsFinalizer(t.DMJob, task.Finalizer) {
		controllerutil.AddFinalizer(t.DMJob, task.Finalizer)
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeuAfter(0)
	}

	switch phase := t.DMJob.Status.Phase; phase {
	case "", v1alpha1.DMJobPhasePending:
		t.DMJob.Status.Phase = v1alpha1.DMJobPhaseCreating
	case v1alpha1.DMJobPhaseCreating, v1alpha1.DMJobPhaseScaling, v1alpha1.DMJobPhaseRunning:
	default:
		return deploy.Panic(fmt.Errorf("unexpected dm job phase during creation: %s", phase))
	}
	return deploy.Done()
}

func (t *Guardian) Delete(ctx context.Context) deploy.Result {
	t.DMJob.Status.Phase = v1alpha1.DMJobPhaseDeleting
	return deploy.Done()
}
