// Code generated by ndpgen. DO NOT EDIT.

package host

import (
	"context"
	"encoding/json"

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

// HTTPSendRequest is the request type for HTTP.Send.
type HTTPSendRequest struct {
	Request HTTPRequest `json:"request"`
}

// HTTPSendResponse is the response type for HTTP.Send.
type HTTPSendResponse struct {
	Result *HTTPResponse `json:"result,omitempty"`
	Error  string        `json:"error,omitempty"`
}

// RegisterHTTPHostFunctions registers HTTP service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterHTTPHostFunctions(service HTTPService) []extism.HostFunction {
	return []extism.HostFunction{
		newHTTPSendHostFunction(service),
	}
}

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

			// Call the service method
			result, svcErr := service.Send(ctx, req.Request)
			if svcErr != nil {
				httpWriteError(p, stack, svcErr)
				return
			}

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

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

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