// Package state contains the state of the enclave.
package state

import (
	"encoding/json"

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

const (
	keyInitialized = "enclave:initialized"
	keyDID         = "enclave:did"
	keyDIDID       = "enclave:did_id"
)

func Default() {
	if pdk.GetVarInt(keyInitialized) == 0 {
		pdk.SetVarInt(keyInitialized, 0)
		pdk.SetVar(keyDID, nil)
		pdk.SetVarInt(keyDIDID, 0)
	}
	pdk.Log(pdk.LogDebug, "state: initialized default state")
}

func IsInitialized() bool {
	return pdk.GetVarInt(keyInitialized) == 1
}

func SetInitialized(v bool) {
	if v {
		pdk.SetVarInt(keyInitialized, 1)
	} else {
		pdk.SetVarInt(keyInitialized, 0)
	}
}

func GetDID() string {
	data := pdk.GetVar(keyDID)
	if data == nil {
		return ""
	}
	return string(data)
}

func SetDID(did string) {
	pdk.SetVar(keyDID, []byte(did))
}

func GetDIDID() int64 {
	return int64(pdk.GetVarInt(keyDIDID))
}

func SetDIDID(id int64) {
	pdk.SetVarInt(keyDIDID, int(id))
}

func GetString(key string) string {
	data := pdk.GetVar(key)
	if data == nil {
		return ""
	}
	return string(data)
}

func SetString(key, value string) {
	pdk.SetVar(key, []byte(value))
}

func GetBytes(key string) []byte {
	return pdk.GetVar(key)
}

func SetBytes(key string, value []byte) {
	pdk.SetVar(key, value)
}

func GetInt(key string) int {
	return pdk.GetVarInt(key)
}

func SetInt(key string, value int) {
	pdk.SetVarInt(key, value)
}

func GetJSON(key string, v any) error {
	data := pdk.GetVar(key)
	if data == nil {
		return nil
	}
	return json.Unmarshal(data, v)
}

func SetJSON(key string, v any) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	pdk.SetVar(key, data)
	return nil
}

func GetConfig(key string) (string, bool) {
	return pdk.GetConfig(key)
}

func MustGetConfig(key string) string {
	val, ok := pdk.GetConfig(key)
	if !ok {
		pdk.SetErrorString("config key required: " + key)
		return ""
	}
	return val
}
