// Code generated by ndpgen. DO NOT EDIT.

package testpkg

import (
	"context"
	"encoding/json"

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

// SearchFindRequest is the request type for Search.Find.
type SearchFindRequest struct {
	Query string `json:"query"`
}

// SearchFindResponse is the response type for Search.Find.
type SearchFindResponse struct {
	Results []Result `json:"results,omitempty"`
	Total   int32    `json:"total,omitempty"`
	Error   string   `json:"error,omitempty"`
}

// RegisterSearchHostFunctions registers Search service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterSearchHostFunctions(service SearchService) []extism.HostFunction {
	return []extism.HostFunction{
		newSearchFindHostFunction(service),
	}
}

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

			// Call the service method
			results, total, svcErr := service.Find(ctx, req.Query)
			if svcErr != nil {
				searchWriteError(p, stack, svcErr)
				return
			}

			// Write JSON response to plugin memory
			resp := SearchFindResponse{
				Results: results,
				Total:   total,
			}
			searchWriteResponse(p, stack, resp)
		},
		[]extism.ValueType{extism.ValueTypePTR},
		[]extism.ValueType{extism.ValueTypePTR},
	)
}

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

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