package task

import (
	"context"
	"fmt"
	"time"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/deploy"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/util"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)

// Guardian adds and removes the finalizer of the LoadBalancer.
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 {
	t.BeginAt = util.Pointer(time.Now())
	// Add finalizer
	if !controllerutil.ContainsFinalizer(t.LoadBalancer, v1alpha1.Finalizer) {
		controllerutil.AddFinalizer(t.LoadBalancer, v1alpha1.Finalizer)
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeuAfter(0)
	}
	switch phase := t.LoadBalancer.Status.Phase; phase {
	case "":
		t.LoadBalancer.Status.Phase = v1alpha1.LoadBalancerPhaseCreating
	case v1alpha1.LoadBalancerPhaseCreating, v1alpha1.LoadBalancerPhaseActive:
	default:
		return deploy.Panic(fmt.Errorf("unexpected phase during creation: %s", phase))
	}
	return deploy.Done()
}
