package workflow

import (
	"context"

	workflowentity "github.com/tidbcloud/fastflow/pkg/entity"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"

	"github.com/tidbcloud/tidb-management-service/tidb-mgmt-service/domain/constant"
)

func Unmarshal(ctx context.Context, clusterId uint64, ins *workflowentity.DagInstance, r proto.Message) proto.Message {
	req, ok := ins.Vars[constant.KeyRequest]
	if !ok {
		return nil
	}

	if err := protojson.Unmarshal([]byte(req.Value), r); err != nil {
		tilog.Error(
			ctx,
			"unmarshal failed",
			zap.Uint64("cluster", clusterId),
			zap.String("value", req.Value),
			zap.Error(err),
		)
		return nil
	}

	return r
}
