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) 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), mutil.PLog(a.oph, r))
		return response.Auto(a.logger, a.Name(), err)
	}
	if !res {
		a.logger.Debug("Access denied when listing organization wallets", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "wallets read permission denied")
	}
	if a.chainGateway == nil {
		return response.Internal(a.logger, mservice.ChainGateway, merrors.Internal("chain gateway client is not configured"))
	}

	req := &chainv1.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)
}
