package ledgerapiimp

import (
	"net/http"

	"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"
	"github.com/tech/sendico/pkg/mutil/mzap"
	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"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func (a *LedgerAPI) listAccounts(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 account 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()
	hasReadPermission, err := a.enf.Enforce(ctx, a.permissionRef, account.ID, orgRef, bson.NilObjectID, model.ActionRead)
	if err != nil {
		a.logger.Warn("Failed to check ledger accounts access permissions", zap.Error(err), mutil.PLog(a.oph, r))
		return response.Auto(a.logger, a.Name(), err)
	}
	if a.client == nil {
		return response.Internal(a.logger, mservice.Ledger, merrors.Internal("ledger client is not configured"))
	}

	req := &ledgerv1.ListAccountsRequest{
		OrganizationRef: orgRef.Hex(),
	}

	// If user has read permission, return all accounts in organization.
	// Otherwise, filter to only accounts owned by the requesting account.
	if !hasReadPermission {
		req.OwnerRefFilter = wrapperspb.String(account.ID.Hex())
		a.logger.Debug("Filtering ledger accounts by owner due to limited permissions",
			mzap.ObjRef("owner_ref", account.ID), mutil.PLog(a.oph, r))
	}

	resp, err := a.client.ListAccounts(ctx, req)
	if err != nil {
		a.logger.Warn("Failed to list ledger accounts", zap.Error(err), mzap.ObjRef("organization_ref", orgRef))
		return response.Auto(a.logger, mservice.Ledger, err)
	}

	return sresponse.LedgerAccounts(a.logger, resp.GetAccounts(), token)
}
