package walletapiimp

import (
	"errors"
	"net/http"
	"strings"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	gatewayv1 "github.com/tech/sendico/pkg/proto/chain/gateway/v1"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.uber.org/zap"
)

func (a *WalletAPI) listWallets(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 list", 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)
	}

	ctx := r.Context()
	res, err := a.enf.Enforce(ctx, a.walletsPermissionRef, account.ID, orgRef, primitive.NilObjectID, model.ActionRead)
	if err != nil {
		a.logger.Warn("Failed to check chain wallet access permissions", zap.Error(err), zap.String(a.oph.Name(), orgRef.Hex()))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !res {
		a.logger.Debug("Access denied when listing organization wallets", zap.String(a.oph.Name(), orgRef.Hex()))
		return response.AccessDenied(a.logger, a.Name(), "wallets read permission denied")
	}
	if a.chainGateway == nil {
		return response.Internal(a.logger, mservice.ChainGateway, errors.New("chain gateway client is not configured"))
	}

	req := &gatewayv1.ListManagedWalletsRequest{
		OrganizationRef: orgRef.Hex(),
	}
	if owner := strings.TrimSpace(r.URL.Query().Get("owner_ref")); owner != "" {
		req.OwnerRef = owner
	}

	resp, err := a.chainGateway.ListManagedWallets(ctx, req)
	if err != nil {
		a.logger.Warn("Failed to list managed wallets", zap.Error(err), zap.String("organization_ref", orgRef.Hex()))
		return response.Auto(a.logger, mservice.ChainGateway, err)
	}

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