// Code generated by ndpgen. DO NOT EDIT.
//
// This file contains client wrappers for the Meta host service.
// It is intended for use in Navidrome plugins built with TinyGo.
//
//go:build wasip1

package ndhost

import (
	"encoding/json"
	"errors"

	"github.com/navidrome/navidrome/plugins/pdk/go/pdk"
)

// meta_get is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user meta_get
func meta_get(uint64) uint64

// meta_set is the host function provided by Navidrome.
//
//go:wasmimport extism:host/user meta_set
func meta_set(uint64) uint64

type metaGetRequest struct {
	Key string `json:"key"`
}

type metaGetResponse struct {
	Value any    `json:"value,omitempty"`
	Error string `json:"error,omitempty"`
}

type metaSetRequest struct {
	Data map[string]any `json:"data"`
}

// MetaGet calls the meta_get host function.
func MetaGet(key string) (any, error) {
	// Marshal request to JSON
	req := metaGetRequest{
		Key: key,
	}
	reqBytes, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	reqMem := pdk.AllocateBytes(reqBytes)
	defer reqMem.Free()

	// Call the host function
	responsePtr := meta_get(reqMem.Offset())

	// Read the response from memory
	responseMem := pdk.FindMemory(responsePtr)
	responseBytes := responseMem.ReadBytes()

	// Parse the response
	var response metaGetResponse
	if err := json.Unmarshal(responseBytes, &response); err != nil {
		return nil, err
	}

	// Convert Error field to Go error
	if response.Error != "" {
		return nil, errors.New(response.Error)
	}

	return response.Value, nil
}

// MetaSet calls the meta_set host function.
func MetaSet(data map[string]any) error {
	// Marshal request to JSON
	req := metaSetRequest{
		Data: data,
	}
	reqBytes, err := json.Marshal(req)
	if err != nil {
		return err
	}
	reqMem := pdk.AllocateBytes(reqBytes)
	defer reqMem.Free()

	// Call the host function
	responsePtr := meta_set(reqMem.Offset())

	// Read the response from memory
	responseMem := pdk.FindMemory(responsePtr)
	responseBytes := responseMem.ReadBytes()

	// Parse error-only response
	var response struct {
		Error string `json:"error,omitempty"`
	}
	if err := json.Unmarshal(responseBytes, &response); err != nil {
		return err
	}
	if response.Error != "" {
		return errors.New(response.Error)
	}
	return nil
}
