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"
	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/bson/primitive"
	"go.uber.org/zap"
)

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()
	res, err := a.enf.Enforce(ctx, a.permissionRef, account.ID, orgRef, primitive.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 !res {
		a.logger.Debug("Access denied when listing ledger accounts", mutil.PLog(a.oph, r))
		return response.AccessDenied(a.logger, a.Name(), "ledger accounts 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.ListAccounts(ctx, &ledgerv1.ListAccountsRequest{
		OrganizationRef: orgRef.Hex(),
	})
	if err != nil {
		a.logger.Warn("Failed to list ledger accounts", zap.Error(err), zap.String("organization_ref", orgRef.Hex()))
		return response.Auto(a.logger, mservice.Ledger, err)
	}

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