package walletapiimp

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"
	chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.uber.org/zap"
)

func (a *WalletAPI) getWalletBalance(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 wallet 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)
	}
	walletRef := strings.TrimSpace(a.wph.GetID(r))
	if walletRef == "" {
		return response.BadReference(a.logger, a.Name(), a.wph.Name(), a.wph.GetID(r), merrors.InvalidArgument("wallet reference is required"))
	}

	ctx := r.Context()
	res, err := a.enf.Enforce(ctx, a.balancesPermissionRef, account.ID, orgRef, primitive.NilObjectID, model.ActionRead)
	if err != nil {
		a.logger.Warn("Failed to check wallet balance permissions", zap.Error(err), mutil.PLog(a.oph, r), zap.String("wallet_ref", walletRef))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !res {
		a.logger.Debug("Access denied when reading wallet balance", mutil.PLog(a.oph, r), zap.String("wallet_ref", walletRef))
		return response.AccessDenied(a.logger, a.Name(), "wallet balance read permission denied")
	}
	if a.chainGateway == nil {
		return response.Internal(a.logger, mservice.ChainGateway, merrors.Internal("chain gateway client is not configured"))
	}

	resp, err := a.chainGateway.GetWalletBalance(ctx, &chainv1.GetWalletBalanceRequest{WalletRef: walletRef})
	if err != nil {
		a.logger.Warn("Failed to fetch wallet balance", zap.Error(err), zap.String("wallet_ref", walletRef))
		return response.Auto(a.logger, mservice.ChainGateway, err)
	}

	bal := resp.GetBalance()
	if bal == nil {
		a.logger.Warn("Wallet balance missing in response", zap.String("wallet_ref", walletRef))
		return response.Auto(a.logger, mservice.ChainGateway, merrors.Internal("wallet balance not available"))
	}

	return sresponse.WalletBalance(a.logger, bal, token)
}
