package aapitemplate

import (
	"errors"
	"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/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *AccountAPI[T]) list(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	ctx := r.Context()
	organizationRef, err := a.Orgph.GetRef(r)
	if err != nil {
		a.Logger.Warn("Failed to restore organization reference", zap.Error(err), mutil.PLog(a.Orgph, r))
		return response.BadReference(a.Logger, a.Name(), a.Orgph.Name(), a.Orgph.GetID(r), err)
	}
	objects, err := a.DB.List(ctx, *account.GetID(), organizationRef)
	if err != nil {
		if !errors.Is(err, merrors.ErrNoData) {
			a.Logger.Warn("Failed to list objects", zap.Error(err), mzap.StorableRef(account))
			return response.Auto(a.Logger, a.Name(), err)
		} else {
			a.Logger.Debug("No objects available", zap.Error(err), mzap.StorableRef(account))
		}
	}
	return a.Objects(objects, accessToken)
}
