// Code generated by Azure.Iot.Operations.ProtocolCompilerLib v0.10.0.0; DO NOT EDIT.
package schemaregistry

import (
	"context"

	"github.com/Azure/iot-operations-sdks/go/protocol"
	"github.com/Azure/iot-operations-sdks/go/protocol/errors"
)

type GetCommandInvoker struct {
	*protocol.CommandInvoker[GetRequestSchema, GetResponseSchema]
}

func NewGetCommandInvoker(
	app *protocol.Application,
	client protocol.MqttClient,
	requestTopic string,
	opt ...protocol.CommandInvokerOption,
) (*GetCommandInvoker, error) {
	var err error
	invoker := &GetCommandInvoker{}

	var opts protocol.CommandInvokerOptions
	opts.Apply(
		opt,
		protocol.WithTopicTokens{
			"commandName": "get",
		},
	)

	invoker.CommandInvoker, err = protocol.NewCommandInvoker(
		app,
		client,
		protocol.JSON[GetRequestSchema]{},
		protocol.JSON[GetResponseSchema]{},
		requestTopic,
		&opts,
	)

	return invoker, err
}

func (invoker GetCommandInvoker) Get(
	ctx context.Context,
	request GetRequestSchema,
	opt ...protocol.InvokeOption,
) (*protocol.CommandResponse[GetResponsePayload], error) {
	invokerOpts := []protocol.InvokeOption{
		protocol.WithTopicTokenNamespace("ex:"),
	}

	var invokeOpts protocol.InvokeOptions
	invokeOpts.Apply(opt, invokerOpts...)

	response, err := invoker.Invoke(
		ctx,
		request,
		&invokeOpts,
	)

	if err != nil {
		return nil, err
	}

	if response.Payload.Error != nil {
		return nil, response.Payload.Error
	}

	if response.Payload.Schema == nil {
		return nil, &errors.Client{
			Message: "Command response has neither normal nor error payload content",
			Kind:    errors.PayloadInvalid{},
			Shallow: false,
		}
	}

	mappedResponse := protocol.CommandResponse[GetResponsePayload]{
		protocol.Message[GetResponsePayload]{
			Payload: GetResponsePayload{
				Schema: *response.Payload.Schema,
			},
			ClientID:        response.ClientID,
			CorrelationData: response.CorrelationData,
			Timestamp:       response.Timestamp,
			TopicTokens:     response.TopicTokens,
			Metadata:        response.Metadata,
		},
	}

	return &mappedResponse, nil
}
