package branch

import (
	"fmt"
	"strings"
	"time"

	"github.com/pingcap/errors"
	controllerutils "github.com/tidbcloud/aws-shared-provider/pkg/controllers/utils"
	"github.com/tidbcloud/aws-shared-provider/pkg/utils"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	infra "github.com/tidbcloud/tidb-management-service/api/serverless_infra"
	"github.com/tidbcloud/tidb-management-service/api/serverless_infra/meta"
	"sigs.k8s.io/controller-runtime/pkg/client"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/equality"
)

func (r *reconcileContext) updateProgress(phase cloudv1.BranchPhase, reason string) error {
	if r.branch.Status.Phase == phase && r.branch.Status.Reason == reason {
		return nil
	}

	oldPhase := r.branch.Status.Phase
	r.Info("[branch lifecycle] branch phase transition",
		"branch", r.branch.Name,
		"from", oldPhase,
		"to", phase,
		"reason", reason,
		"age", time.Since(r.branch.CreationTimestamp.Time).Round(time.Second),
	)
	r.InfraRecorder.Event(r.branch, corev1.EventTypeNormal, string(phase), reason)

	if err := r.ensureStatus(func(
		status *cloudv1.BranchStatus,
		_ *cloudv1.AwsFreeTierClusterStatus,
	) error {
		status.Phase = phase
		status.Reason = reason
		return nil
	}); err != nil {
		return fmt.Errorf("update progress err: %w", err)
	}

	return nil
}

// ensureStatus update the cluster status if necessary.
func (r *reconcileContext) ensureStatus(mutateFn func(
	*cloudv1.BranchStatus, *cloudv1.AwsFreeTierClusterStatus,
) error) error {
	// ensure the branch status is decoded.
	branchStatus, err := r.branch.AwsFreeTierClusterStatusFromBranch()
	if err != nil {
		return err
	}
	r.branch.SetAwsFreeTierClusterStatus(branchStatus)

	old := r.branch.Status.DeepCopy()

	if err = mutateFn(
		&r.branch.Status,
		r.branch.Status.FromProvider.Object.(*cloudv1.AwsFreeTierClusterStatus),
	); err != nil {
		return err
	}

	if equality.Semantic.DeepEqual(old, &r.branch.Status) {
		// no changed, skip updating
		// Note: the local status may not be same as the truth, but we will reach eventually-consistency via reconciliation
		return nil
	}

	return r.InfraClient.Status().Update(r.ctx, r.branch)
}

func (r *reconcileContext) getParentKeyspace() (string, error) {
	parentBranchID, exist := r.branch.Annotations[ParentBranchIdAnnKey]
	if !exist {
		return "", errors.New("parent branch id not found")
	}

	parentType, exist := r.branch.Annotations[ParentTypeAnnKey]
	if !exist {
		return "", errors.New("parent type not found")
	}

	var parentKeyspace string
	switch parentType {
	case ParentTypeCluster:
		if strings.Contains(r.branch.Namespace, "test") {
			/* e2e test namespace */
			cluster := &infra.Cluster{ObjectMeta: meta.ObjectMeta{Namespace: r.branch.Namespace, Name: parentBranchID}}
			err := r.InfraClusterCli.Get(r.ctx, cluster)
			if err != nil {
				return "", errors.Wrap(err, "failed to get parent cluster")
			}
			return cluster.Status.KeyspaceToken, nil
		}
		nsPrefix, projectId, err := controllerutils.ParseNamespacePrefixAndProjectID(r.branch.Namespace)
		if err != nil {
			return "", errors.Wrap(err, "parse namespace")
		}
		cluster, err := controllerutils.GetInfraCluster(r.ctx, r.InfraClusterCli, nsPrefix, parentBranchID, projectId)
		if err != nil {
			return "", errors.Wrap(err, "failed to get parent cluster")
		}
		// the cluster infra might not be latest due to outdated cache even the control plane check passes, retry later
		if cluster.Status.Phase != infra.ClusterPhaseRunning {
			return "", &utils.RequeueAfterError{Cause: errors.New("parent cluster is not running"), RequeueAfter: 15 * time.Second}
		}
		parentKeyspace = cluster.Status.KeyspaceToken
	case ParentTypeBranch:
		branch := &cloudv1.Branch{}
		err := r.InfraClient.Get(r.ctx, client.ObjectKey{Namespace: r.branch.Namespace, Name: parentBranchID},
			branch)
		if err != nil {
			return "", errors.Wrap(err, "failed to get parent branch")
		}
		clusterStatus, err := branch.AwsFreeTierClusterStatusFromBranch()
		if err != nil {
			return "", err
		}
		parentKeyspace = clusterStatus.KeyspaceToken
	default:
		return "", fmt.Errorf("unknown parent type %s", parentType)
	}
	return parentKeyspace, nil
}
