// Code generated by ndpgen. DO NOT EDIT.

package testpkg

import (
	"context"
	"encoding/json"

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

// ListItemsRequest is the request type for List.Items.
type ListItemsRequest struct {
	Name   string `json:"name"`
	Filter Filter `json:"filter"`
}

// ListItemsResponse is the response type for List.Items.
type ListItemsResponse struct {
	Count int32  `json:"count,omitempty"`
	Error string `json:"error,omitempty"`
}

// RegisterListHostFunctions registers List service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterListHostFunctions(service ListService) []extism.HostFunction {
	return []extism.HostFunction{
		newListItemsHostFunction(service),
	}
}

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

			// Call the service method
			count, svcErr := service.Items(ctx, req.Name, req.Filter)
			if svcErr != nil {
				listWriteError(p, stack, svcErr)
				return
			}

			// Write JSON response to plugin memory
			resp := ListItemsResponse{
				Count: count,
			}
			listWriteResponse(p, stack, resp)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

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

// listWriteError writes an error response to plugin memory.
func listWriteError(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
}
