package app

import (
	"fmt"

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

func GetAccountingRulesetsByAccountID(
	accountID string,
	principal *User,
) (map[string]*ledger_models.AccountingRuleset, error) {
	obj, ok := accountingRulesetCache.get(accountID)
	if ok {
		sugar.Debugf("ops.getAccountingRulesetsByAccountID: 👍 📤 🎯 n = %v", len(obj))
		return obj, nil
	}
	params := accounting_ruleset.NewGetAccountingRulesetsParamsWithTimeout(getTimeout)
	params.AccountID = accountID
	response, restErr := ledgerClient.AccountingRuleset.GetAccountingRulesets(params, principal.Auth)
	if restErr != nil {
		return nil, fmt.Errorf("ops.getAccountingRulesetsByAccountID: 💣 ⛔ %w", restErr)
	}
	theRulesets := map[string]*ledger_models.AccountingRuleset{}
	for _, itm := range response.Payload.Data {
		theRulesets[itm.Code] = itm
	}
	sugar.Debugf("ops.getAccountingRulesetsByAccountID: 👍 📤 n = %v", len(theRulesets))
	accountingRulesetCache.put(accountID, theRulesets)
	return theRulesets, nil
}
