// Code generated by ndpgen. DO NOT EDIT.

package testpkg

import (
	"context"
	"encoding/json"

	extism "github.com/extism/go-sdk"
)

// CodecEncodeRequest is the request type for Codec.Encode.
type CodecEncodeRequest struct {
	Data []byte `json:"data"`
}

// CodecEncodeResponse is the response type for Codec.Encode.
type CodecEncodeResponse struct {
	Result []byte `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// RegisterCodecHostFunctions registers Codec service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterCodecHostFunctions(service CodecService) []extism.HostFunction {
	return []extism.HostFunction{
		newCodecEncodeHostFunction(service),
	}
}

func newCodecEncodeHostFunction(service CodecService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"codec_encode",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
			// Read JSON request from plugin memory
			reqBytes, err := p.ReadBytes(stack[0])
			if err != nil {
				codecWriteError(p, stack, err)
				return
			}
			var req CodecEncodeRequest
			if err := json.Unmarshal(reqBytes, &req); err != nil {
				codecWriteError(p, stack, err)
				return
			}

			// Call the service method
			result, svcErr := service.Encode(ctx, req.Data)
			if svcErr != nil {
				codecWriteError(p, stack, svcErr)
				return
			}

			// Write JSON response to plugin memory
			resp := CodecEncodeResponse{
				Result: result,
			}
			codecWriteResponse(p, stack, resp)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

// codecWriteResponse writes a JSON response to plugin memory.
func codecWriteResponse(p *extism.CurrentPlugin, stack []uint64, resp any) {
	respBytes, err := json.Marshal(resp)
	if err != nil {
		codecWriteError(p, stack, err)
		return
	}
	respPtr, err := p.WriteBytes(respBytes)
	if err != nil {
		stack[0] = 0
		return
	}
	stack[0] = respPtr
}

// codecWriteError writes an error response to plugin memory.
func codecWriteError(p *extism.CurrentPlugin, stack []uint64, err error) {
	errResp := struct {
		Error string `json:"error"`
	}{Error: err.Error()}
	respBytes, _ := json.Marshal(errResp)
	respPtr, _ := p.WriteBytes(respBytes)
	stack[0] = respPtr
}
