package papitemplate

import (
	"encoding/json"
	"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 *ProtectedAPI[T]) update(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	var object T
	if err := json.NewDecoder(r.Body).Decode(&object); err != nil {
		a.Logger.Warn("Failed to decode object when updating settings", zap.Error(err), mzap.StorableRef(account))
		return response.BadPayload(a.Logger, a.Name(), err)
	}

	if err := a.DB.Update(r.Context(), *account.GetID(), &object); err != nil {
		a.Logger.Warn("Error updating object", zap.Error(err), mzap.StorableRef(account))
		return response.Auto(a.Logger, a.Name(), err)
	}

	if err := a.nconfig.UpdateNotification(&object, *account.GetID()); err != nil {
		a.Logger.Warn("Failed to send creation notification", zap.Error(err))
	}

	return a.Object(&object, accessToken)
}
