package action

import (
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/clusterconfig"
	"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"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"google.golang.org/protobuf/encoding/protojson"
)

type CreateTiDBGroupConfigAction struct {
	tidbGroupRepo       repo.TiDBGroupRepo
	clusterConfigClient clusterconfig.Client
}

const CreateTiDBGroupConfigName = "create-tidb-group-config"

func NewCreateTiDBGroupConfigAction(
	tidbGroupRepo repo.TiDBGroupRepo,
	clusterConfigClient clusterconfig.Client,
) actions.Action {
	return &CreateTiDBGroupConfigAction{
		tidbGroupRepo:       tidbGroupRepo,
		clusterConfigClient: clusterConfigClient,
	}
}

func (a *CreateTiDBGroupConfigAction) Name() string {
	return CreateTiDBGroupConfigName
}

// Invoke creates tidb cluster cr in dataplane
func (a *CreateTiDBGroupConfigAction) Invoke(args actions.ActionArgs) error {
	// generate context
	ctx := utils.GenerateContext(args)
	tilog.Info(ctx, "create tidb group config action invoked")

	tidbGroupStr, err := args.GetString(workflow.TiDBGroupKey)
	if err != nil {
		return fmt.Errorf("failed to get tidb group: %w", err)
	}

	var tidbGroup entity.TiDBGroup
	err = protojson.Unmarshal([]byte(tidbGroupStr), &tidbGroup)
	if err != nil {
		tilog.Error(ctx, "failed to unmarshal tidb group", zap.Error(err))
		return fmt.Errorf("failed to unmarshal tidb group: %w", err)
	}

	err = a.clusterConfigClient.CreateTiDBGroupConfig(ctx, &tidbGroup)
	if err != nil {
		tilog.Error(ctx, "failed to create tidb group config", zap.Error(err))
		return fmt.Errorf("failed to create tidb group config: %w", err)
	}

	return nil
}
