package ledgerapiimp

import (
	"net/http"
	"strings"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func (a *LedgerAPI) getBalance(r *http.Request, account *model.Account, token *sresponse.TokenData) http.HandlerFunc {
	orgRef, err := a.oph.GetRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization reference for ledger balance", zap.Error(err), zap.String(a.oph.Name(), a.oph.GetID(r)))
		return response.BadReference(a.logger, a.Name(), a.oph.Name(), a.oph.GetID(r), err)
	}

	accountRef := strings.TrimSpace(a.aph.GetID(r))
	if accountRef == "" {
		return response.BadReference(a.logger, a.Name(), a.aph.Name(), a.aph.GetID(r), merrors.InvalidArgument("ledger account reference is required"))
	}

	ctx := r.Context()
	res, err := a.enf.Enforce(ctx, a.balancePerm, account.ID, orgRef, bson.NilObjectID, model.ActionRead)
	if err != nil {
		a.logger.Warn("Failed to check ledger balance access permissions", zap.Error(err), mutil.PLog(a.oph, r), zap.String("ledger_account_ref", accountRef))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !res {
		a.logger.Debug("Access denied when reading ledger balance", mutil.PLog(a.oph, r), zap.String("ledger_account_ref", accountRef))
		return response.AccessDenied(a.logger, a.Name(), "ledger balance read permission denied")
	}
	if a.client == nil {
		return response.Internal(a.logger, mservice.Ledger, merrors.Internal("ledger client is not configured"))
	}

	resp, err := a.client.GetBalance(ctx, &ledgerv1.GetBalanceRequest{
		LedgerAccountRef: accountRef,
	})
	if err != nil {
		a.logger.Warn("Failed to fetch ledger balance", zap.Error(err), zap.String("ledger_account_ref", accountRef))
		return response.Auto(a.logger, mservice.Ledger, err)
	}

	return sresponse.LedgerBalance(a.logger, resp, token)
}
