package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/ledger/ledger_client/accounting_rule"
	"code.tnxs.net/taxnexus/lib/api/ledger/ledger_models"
)

// GetAccountingRulesByAccountID is a first class object retrieval method
func GetAccountingRulesByAccountID(
	accountID string,
	principal *User,
) (map[string]*ledger_models.AccountingRule, error) {
	sugar.Debug("ops.getAccountingRulesByAccountID: 📥")
	obj, ok := accountingRuleCache.get(accountID)
	if ok {
		sugar.Debugf("ops.getAccountingRulesByAccountID: 👍 📤 🎯 n = %v", len(obj))
		return obj, nil
	}
	ledgerParams := accounting_rule.NewGetAccountingRulesParamsWithTimeout(getTimeout)
	ledgerParams.AccountID = accountID
	response, restErr := ledgerClient.AccountingRule.GetAccountingRules(ledgerParams, principal.Auth)
	if restErr != nil {
		return nil, fmt.Errorf("ops.getAccountingRulesByAccountID: 💣 ⛔ %w", restErr)
	}
	theRules := map[string]*ledger_models.AccountingRule{}
	for _, itm := range response.Payload.Data {
		theRules[itm.Code] = itm
	}
	sugar.Debugf("ops.getAccountingRulesByAccountID: 👍 📤 n = %v", len(theRules))
	accountingRuleCache.put(accountID, theRules)
	return theRules, nil
}
