package br

import (
	"fmt"

	dplanemgrv1 "github.com/tidbcloud/cluster-service-ng/api/dataplane-manager/v1"
	"github.com/tidbcloud/cluster-service-ng/config"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"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/utils"
)

const ValidateTiBRAutoBackupPlacementActionName = "validate-tibr-auto-backup-placement"

type validateTiBRAutoBackupPlacementAction struct {
	sharedPoolRepo repo.SharedPoolRepo
	dpServiceCli   dplanemgrv1.DataPlaneServiceClient
	bizConfig      *config.BizConfig
}

func NewValidateTiBRAutoBackupPlacementAction(
	sharedPoolRepo repo.SharedPoolRepo,
	dpServiceCli dplanemgrv1.DataPlaneServiceClient,
	bizConfig *config.BizConfig,
) actions.Action {
	return &validateTiBRAutoBackupPlacementAction{
		sharedPoolRepo: sharedPoolRepo,
		dpServiceCli:   dpServiceCli,
		bizConfig:      bizConfig,
	}
}

func (a *validateTiBRAutoBackupPlacementAction) Name() string {
	return ValidateTiBRAutoBackupPlacementActionName
}

func (a *validateTiBRAutoBackupPlacementAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	sharedPoolID, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return fmt.Errorf("failed to get sharedPool id: %w", err)
	}
	sharedPool, err := a.sharedPoolRepo.Load(ctx, sharedPoolID, false)
	if err != nil {
		return fmt.Errorf("failed to load sharedPool: %w", err)
	}
	_, err = resolveTiBRAutoBackupPlacement(ctx, a.dpServiceCli, a.bizConfig, sharedPool)
	if err != nil {
		return fmt.Errorf("failed to validate tibr auto backup placement: %w", err)
	}
	return nil
}
