package common

import (
	"context"
	"fmt"

	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/deploy"
	"github.com/tidbcloud/observability/pkg/resourceworker/controllers/serverless/task"
)

// Guardian guards the deletion and creation of the o11y 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"
}

// Create validates or initializes the o11y cluster phase.
func (t *Guardian) Create(ctx context.Context) deploy.Result {
	// ignore resource that doesn't belong to this region

	switch phase := t.Cluster.Status.Phase; phase {
	case "":
		t.Cluster.Status.Phase = constants.CREATING
	case constants.CREATING, constants.UPDATING, constants.ACTIVE:
	default:
		return deploy.Panic(fmt.Errorf("unexpected serverless cluster phase during creation: %s", phase))
	}

	return deploy.Done()
}

func (t *Guardian) Delete(ctx context.Context) deploy.Result {
	switch phase := t.Cluster.Status.Phase; phase {
	case constants.CREATING, constants.ACTIVE, "":
		t.Cluster.Status.Phase = constants.DELETING
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeueAfter(0)
	case constants.DELETING:
	default:
		return deploy.Panic(fmt.Errorf("unexpected serverless cluster phase during deletion: %s", phase))
	}
	return deploy.Done()
}
