package action

import (
	"context"
	"fmt"

	"github.com/pingcap/tidb-operator/api/v2/core/v1alpha1"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/dataplane"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/repo"
	"github.com/tidbcloud/cluster-service-ng/pkg/tioperator"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

const EnsureClusterUpgradePolicyActionName = "ensure-cluster-upgrade-policy"

type EnsureClusterUpgradePolicyAction struct {
	sharedPoolRepo   repo.SharedPoolRepo
	dataplaneManager dataplane.Manager
}

func NewEnsureClusterUpgradePolicyAction(
	sharedPoolRepo repo.SharedPoolRepo,
	dataplaneManager dataplane.Manager,
) actions.AsyncAction {
	return &EnsureClusterUpgradePolicyAction{
		sharedPoolRepo:   sharedPoolRepo,
		dataplaneManager: dataplaneManager,
	}
}

func (a *EnsureClusterUpgradePolicyAction) Name() string {
	return EnsureClusterUpgradePolicyActionName
}

func (a *EnsureClusterUpgradePolicyAction) Start(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	required, err := shouldEnsureNoConstraintsUpgradePolicy(args)
	if err != nil {
		return err
	}
	if !required {
		tilog.Info(ctx, "cluster upgrade policy enforcement is not required")
		return nil
	}

	sharedPoolID, remoteCli, err := a.loadRemoteClient(ctx, args)
	if err != nil {
		return err
	}
	if err := tioperator.UpdateClusterUpgradePolicy(
		ctx,
		remoteCli,
		sharedPoolID,
		v1alpha1.UpgradePolicyNoConstraints,
	); err != nil {
		return err
	}

	tilog.Info(
		ctx,
		"cluster upgrade policy ensured",
		zap.String("sharedPoolId", sharedPoolID),
		zap.String("upgradePolicy", string(v1alpha1.UpgradePolicyNoConstraints)),
	)
	return nil
}

func (a *EnsureClusterUpgradePolicyAction) CheckFinish(args actions.ActionArgs) (bool, error) {
	ctx := utils.GenerateContext(args)
	required, err := shouldEnsureNoConstraintsUpgradePolicy(args)
	if err != nil {
		return false, err
	}
	if !required {
		return true, nil
	}

	sharedPoolID, remoteCli, err := a.loadRemoteClient(ctx, args)
	if err != nil {
		return false, err
	}
	observed, err := tioperator.IsClusterUpgradePolicyObserved(
		ctx,
		remoteCli,
		sharedPoolID,
		v1alpha1.UpgradePolicyNoConstraints,
	)
	if err != nil {
		return false, err
	}
	if !observed {
		tilog.Info(
			ctx,
			"waiting for cluster upgrade policy to be observed",
			zap.String("sharedPoolId", sharedPoolID),
		)
		return false, nil
	}

	tilog.Info(
		ctx,
		"cluster upgrade policy enforcement completed",
		zap.String("sharedPoolId", sharedPoolID),
	)
	return true, nil
}

func (a *EnsureClusterUpgradePolicyAction) loadRemoteClient(
	ctx context.Context,
	args actions.ActionArgs,
) (string, client.Client, error) {
	sharedPoolID, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return "", nil, fmt.Errorf("failed to get sharedPool id: %w", err)
	}
	sharedPool, err := a.sharedPoolRepo.Load(ctx, sharedPoolID, false)
	if err != nil {
		return "", nil, fmt.Errorf("failed to load sharedPool: %w", err)
	}
	remoteCli, err := a.dataplaneManager.GetClient(sharedPool.GetDataplaneName())
	if err != nil {
		return "", nil, fmt.Errorf("failed to get remote client for shared pool: %w", err)
	}
	return sharedPoolID, remoteCli, nil
}

func shouldEnsureNoConstraintsUpgradePolicy(args actions.ActionArgs) (bool, error) {
	if _, exists := args[workflow.EnsureNoConstraintsUpgradePolicyKey]; !exists {
		return false, nil
	}

	required, err := args.GetBool(workflow.EnsureNoConstraintsUpgradePolicyKey)
	if err != nil {
		return false, fmt.Errorf("failed to get cluster upgrade policy flag: %w", err)
	}
	return required, nil
}
