package papitemplate

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

func (a *ProtectedAPI[T]) list(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	organizationRef, err := a.Oph.GetRef(r)
	if err != nil {
		a.Logger.Warn("Failed to restore organization reference", zap.Error(err), mutil.PLog(a.Oph, r))
		return response.BadReference(a.Logger, a.Name(), a.Oph.Name(), a.Oph.GetID(r), err)
	}
	parentRef, err := a.Pph.GetRef(r)
	if err != nil {
		a.Logger.Warn("Failed to restore parent reference", zap.Error(err), mutil.PLog(a.Pph, r))
		return response.BadReference(a.Logger, a.Name(), a.Pph.Name(), a.Pph.GetID(r), err)
	}

	cursor, err := mutil.GetViewCursor(a.Logger, r)
	if err != nil {
		a.Logger.Warn("Failed to decode view cursor", zap.Error(err))
		return response.Auto(a.Logger, a.Name(), err)
	}
	objects, err := a.DB.List(r.Context(), *account.GetID(), organizationRef, parentRef, cursor)
	if err != nil {
		if !errors.Is(err, merrors.ErrNoData) {
			a.Logger.Warn("Failed to list objects", zap.Error(err), mutil.PLog(a.Pph, r))
			return response.Auto(a.Logger, a.Name(), err)
		} else {
			a.Logger.Debug("No objects available", zap.Error(err), mutil.PLog(a.Pph, r))
		}
	}
	return a.Objects(objects, accessToken)
}
