package app

import (
	"code.tnxs.net/taxnexus/lib/api/ledger/ledger_client/gl_balance"
	"code.tnxs.net/taxnexus/lib/api/ledger/ledger_models"
)

// GlBalanceParams is a parameter struct
type GlBalanceParams struct {
	glAccountID string
	periodID    string
	principal   *User
}

// GetGlBalanceByParams is a GL balance helper function
func GetGlBalanceByParams(params GlBalanceParams) *ledger_models.GlBalance {
	sugar.Debug("ops.getGlBalanceByParams: 📥")
	obj, ok := glBalanceCache.get(params.periodID, params.glAccountID)
	if ok {
		sugar.Debug("ops.getGlBalanceByParams: 👍 📤 🎯")
		return obj
	}
	ledgerParams := gl_balance.NewGetGlBalancesParamsWithTimeout(getTimeout)
	ledgerParams.GlAccountID = &params.glAccountID
	ledgerParams.PeriodID = &params.periodID
	response, restErr := ledgerClient.GlBalance.GetGlBalances(ledgerParams, params.principal.Auth)
	if restErr != nil {
		sugar.Errorf("ops.getGlBalanceByParams: 💣 ⛔ %s", restErr.Error())
		return nil
	}
	theGlBalance := &ledger_models.GlBalance{}
	for _, itm := range response.Payload.Data {
		theGlBalance = itm // singleton
	}
	glBalanceCache.put(params.periodID, params.glAccountID, theGlBalance)
	sugar.Debugf("ops.getGlBalanceByParams: 👍 📤")
	return theGlBalance
}
