package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/crm/crm_client/contacts"
)

// GetContact is a first class object retrieval function
func GetContact(id string, principal *User) *Contact {
	if id == "" {
		return nil
	}
	c, ok := contactCache.get(id)
	if ok {
		return c
	}
	c, err := GetContactByID(id, principal)
	if err != nil {
		return nil
	}
	return c
}

// GetContactByID is a first class object retrieval function
func GetContactByID(key string, principal *User) (*Contact, error) {
	sugar.Debugf("render.getContactByID: 📥")
	if key == "" {
		return nil, fmt.Errorf("render.getContactByID: 💣 ⛔ key is blank")
	}
	obj, ok := contactCache.get(key)
	if ok {
		sugar.Debugf("render.getContactByID: 👍 🎯 📤")
		return obj, nil
	}
	params := contacts.NewGetContactsParams()
	params.ContactID = &key
	response, err := crmClient.Contacts.GetContacts(params, principal.Auth)
	if err != nil {
		return nil, err
	}
	var newObj *Contact
	for _, itm := range response.Payload.Data { // single iteration execution
		newObj = UnMarshalContact(itm)
	}
	contactCache.put(key, newObj)
	sugar.Debugf("render.getContactByID: 👍 🆕 📤")
	return newObj, nil
}
