// Code generated by ndpgen. DO NOT EDIT.

package host

import (
	"context"
	"encoding/json"

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

// UsersGetUsersResponse is the response type for Users.GetUsers.
type UsersGetUsersResponse struct {
	Result []User `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// UsersGetAdminsResponse is the response type for Users.GetAdmins.
type UsersGetAdminsResponse struct {
	Result []User `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

// RegisterUsersHostFunctions registers Users service host functions.
// The returned host functions should be added to the plugin's configuration.
func RegisterUsersHostFunctions(service UsersService) []extism.HostFunction {
	return []extism.HostFunction{
		newUsersGetUsersHostFunction(service),
		newUsersGetAdminsHostFunction(service),
	}
}

func newUsersGetUsersHostFunction(service UsersService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"users_getusers",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {

			// Call the service method
			result, svcErr := service.GetUsers(ctx)
			if svcErr != nil {
				usersWriteError(p, stack, svcErr)
				return
			}

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

func newUsersGetAdminsHostFunction(service UsersService) extism.HostFunction {
	return extism.NewHostFunctionWithStack(
		"users_getadmins",
		func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {

			// Call the service method
			result, svcErr := service.GetAdmins(ctx)
			if svcErr != nil {
				usersWriteError(p, stack, svcErr)
				return
			}

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

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

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