package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/geo/geo_client/county"
	"code.tnxs.net/taxnexus/lib/api/geo/geo_models"
)

// GetCountyNameByGeocode is first class retrieval function
func GetCountyNameByGeocode(key string, principal *User) string {
	if key == "" {
		return ""
	}
	if len(key) == countyGeocodeLength {
		c, ok := countyCache.get(key)
		if ok {
			return c.Name
		}
		obj, err := GetCountyByGeocode(key, principal)
		if err != nil {
			return ""
		}
		return obj.Name
	}
	obj, ok := placeCache.get(key)
	if ok {
		return obj.SalesTaxRate.County
	}
	place, err := GetPlaceByGeocode(key, principal)
	if err != nil {
		return ""
	}
	return place.SalesTaxRate.County
}

// GetCountyByGeocode is first class retrieval function
func GetCountyByGeocode(recordID string, principal *User) (geo_models.County, error) {
	sugar.Debug("plex.getCountyByGeocode: 📥")
	if recordID == "" {
		return geo_models.County{}, fmt.Errorf("plex.getCountyByID: 💣 ⛔ key is blank")
	}
	obj, ok := countyCache.get(recordID)
	if ok {
		sugar.Debug("plex.getCountyByGeocode: 👍 🎯 📤")
		return *obj, nil
	}
	geoParams := county.NewGetCountiesParamsWithTimeout(getTimeout)
	geoParams.Geocode = &recordID
	response, err := geoClient.County.GetCounties(geoParams, principal.Auth)
	if err != nil {
		return geo_models.County{}, err
	}
	var newObj *geo_models.County
	for _, itm := range response.Payload.Data { // single iteration execution
		newObj = itm
	}
	countyCache.put(recordID, newObj)
	sugar.Debug("plex.getCountyByGeocode: 👍 🆕 📤")
	return *newObj, nil
}
