You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: setting_marshal.go
    path of file: ./repos/corteza/server/pkg/envoy/store
    
    the code of the file until where you have to start completion: package store

import (
	"context"

	"github.com/cortezaproject/corteza/server/pkg/envoy/resource"
	"github.com/cortezaproject/corteza/server/store"
	"github.com/cortezaproject/corteza/server/system/types"
)

    
func (n *setting) Encode(ctx context.Context, pl *payload) (err error) {
	res := n.st

	us, err := resolveUserstamps(ctx, pl.s, pl.state.ParentResources, n.res.Userstamps())
	if err != nil {
		return err
	}

	ts := n.res.Timestamps()
	if ts != nil {
		if ts.UpdatedAt != nil {
			res.UpdatedAt = *ts.UpdatedAt.T
		} else {
			res.UpdatedAt = *now()
		}
	} else {
		res.UpdatedAt = *now()
	}

	if us != nil {
		if us.OwnedBy != nil {
			res.OwnedBy = us.OwnedBy.UserID
		}
		if us.UpdatedBy != nil {
			res.UpdatedBy = us.UpdatedBy.UserID
		}
	}

	if _, exists := gSettings[res.Name]; !exists {
		return store.CreateSettingValue(ctx, pl.s, res)
	}

	// On existing setting, replace/merge right basically overwrites the existing value;
	// otherwise, the new value is ignored.
	switch n.cfg.OnExisting {
	case resource.Replace,
		resource.MergeRight:
		return store.UpdateSettingValue(ctx, pl.s, res)
	}

	return nil
}