package task

import (
	"context"

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

	"github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/pkg/consts"
	"github.com/tidbcloud/infra-provider/pkg/deploy"
)

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.Logger.Info("create guardian", "name", t.PLEndpoint.Name)
	// prevent reconciling objects from different regions
	if t.Config.Provider == consts.ProviderTypeEKS && t.Network != nil && t.Network.Spec.Region != t.Config.Network.Region {
		return deploy.Panic(nil)
	}

	t.Logger.Info("add finalizer to private link endpoint", "name", t.PLEndpoint.Name)
	if !controllerutil.ContainsFinalizer(t.PLEndpoint, Finalizer) {
		controllerutil.AddFinalizer(t.PLEndpoint, Finalizer)
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeuAfter(0)
	}

	t.PLEndpoint.Status.ErrorMessage = ""
	switch phase := t.PLEndpoint.Status.Phase; phase {
	case "", v1alpha1.PrivateLinkEndpointPhaseError, v1alpha1.PrivateLinkEndpointPhaseCreating:
		t.Logger.Info("set private link endpoint phase to creating", "name", t.PLEndpoint.Name)
		t.PLEndpoint.Status.Phase = v1alpha1.PrivateLinkEndpointPhaseCreating
	default:
	}
	t.Logger.Info("private link endpoint phase", "name", t.PLEndpoint.Name, "phase", t.PLEndpoint.Status.Phase)
	return deploy.Done()
}

func (t *Guardian) Delete(ctx context.Context) deploy.Result {
	t.Logger.Info("delete private link endpoint", "name", t.PLEndpoint.Name)
	switch phase := t.PLEndpoint.Status.Phase; phase {
	case v1alpha1.PrivateLinkEndpointPhaseDeleting:
	default:
		t.PLEndpoint.Status.Phase = v1alpha1.PrivateLinkEndpointPhaseDeleting
	}
	t.Logger.Info("private link endpoint phase", "name", t.PLEndpoint.Name, "phase", t.PLEndpoint.Status.Phase)
	return deploy.Done()
}
