package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/regs/regs_client/backend"
)

// GetBackend is a first class object retrieval function
func GetBackend(id string, principal *User) *Backend {
	if id == "" {
		return nil
	}
	c, ok := backendCache.get(id)
	if ok {
		return c
	}
	c, err := GetBackendByID(id, principal)
	if err != nil {
		return nil
	}
	return c
}

// GetBackendByID is a first class object retrieval function
func GetBackendByID(key string, principal *User) (*Backend, error) {
	sugar.Debugf("app.getBackendByID: 📥")
	if key == "" {
		return nil, fmt.Errorf("app.getBackendByID: 💣 ⛔ key is blank")
	}
	obj, ok := backendCache.get(key)
	if ok {
		sugar.Debugf("app.getBackendByID: 👍 🎯 📤")
		return obj, nil
	}
	params := backend.NewGetBackendsParamsWithTimeout(getTimeout)
	params.BackendID = &key
	response, err := regsClient.Backend.GetBackends(params, principal.Auth)
	if err != nil {
		return nil, err
	}
	var newObj *Backend
	for _, itm := range response.Payload.Data { // single iteration execution
		newObj = UnMarshalBackend(itm)
	}
	backendCache.put(key, newObj)
	sugar.Debugf("app.getBackendByID: 👍 🆕 📤")
	return newObj, nil
}
