package aapitemplate

import (
	"context"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"go.uber.org/zap"
)

func (a *AccountAPI[T]) reorder(r *http.Request, account *model.Account, _ *sresponse.TokenData) http.HandlerFunc {
	a.Logger.Debug("Processing reorder request...")
	req, filter, err := a.config.Reorder.ReqProcessor(r)
	if err != nil {
		a.Logger.Warn("Failed to decode tasks reorder request", zap.Error(err), mzap.StorableRef(account))
		return response.BadPayload(a.Logger, a.Name(), err)
	}
	a.Logger.Debug("Moving objects", mzap.ObjRef("object_ref", req.ObjectRef), zap.Int("new_index", req.To))

	if _, err := a.a.DBFactory().TransactionFactory().CreateTransaction().Execute(r.Context(), func(ctx context.Context) (any, error) {
		// reorder is not atomic, so wrappping into transaction
		return nil, a.config.Reorder.DB.Reorder(ctx, account.ID, req.ObjectRef, req.To, filter)
	}); err != nil {
		a.Logger.Warn("Failed to reorder tasks", zap.Error(err), mzap.ObjRef("object_ref", req.ObjectRef), zap.Int("to", req.To))
		return response.Auto(a.Logger, a.Name(), err)
	}

	a.Logger.Debug("Reorder request processing complete")
	return response.Success(a.Logger)
}
