package common

import (
	"context"
	"fmt"
	"time"

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

// Guardian adds and removes the finalizer of the VPC.
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 {
	// TODO: check region
	// Add finalizer
	if !controllerutil.ContainsFinalizer(t.PrivateLinkService, v1alpha1.Finalizer) {
		controllerutil.AddFinalizer(t.PrivateLinkService, v1alpha1.Finalizer)
		// Require immediate requeue without running other tasks
		return deploy.Panic(nil).WithRequeuAfter(0)
	}

	defer func() {
		if err := t.PrivateLinkServiceRW.UpdateStatus(ctx, t.PrivateLinkService); err != nil {
			t.Logger.Error(err, "failed to update internet status")
		}
	}()

	// Check vpc phase
	switch phase := t.PrivateLinkService.Status.Phase; phase {
	case "", v1alpha1.PrivateLinkServicePhasePending:
		active := t.waitVPCActive(ctx)
		if !active {
			t.Logger.Info("VPC is not active yet, waiting for it to be active")
			t.PrivateLinkService.Status.Phase = v1alpha1.PrivateLinkServicePhasePending
			return deploy.Panic(nil).WithRequeuAfter(time.Second * 30)
		}
		t.PrivateLinkService.Status.Phase = v1alpha1.PrivateLinkServicePhaseReadyForCreate
		return deploy.Panic(nil).WithRequeuAfter(0)
	case v1alpha1.PrivateLinkServicePhaseReadyForCreate, v1alpha1.PrivateLinkServicePhaseFailed:
		t.PrivateLinkService.Status.Phase = v1alpha1.PrivateLinkServicePhaseCreating
	case v1alpha1.PrivateLinkServicePhaseCreating, v1alpha1.PrivateLinkServicePhaseActive:
	default:
		return deploy.Panic(fmt.Errorf("unexpected PrivateLinkService phase during creation: %s", phase))
	}

	return deploy.Done()
}

func (t *Guardian) waitVPCActive(ctx context.Context) bool {
	if t.VPC.Status.Phase == v1alpha1.VPCPhaseActive {
		t.PrivateLinkService.Status.VPCID = t.VPC.Status.VPC.VPCID
		return true
	}

	return false
}

func (t *Guardian) Delete(ctx context.Context) deploy.Result {
	// TODO: check internet phase
	return deploy.Done()
}
