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

func (a *ProtectedAPI[T]) create(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 parse parent object reference", zap.Error(err), mutil.PLog(a.Oph, r))
		return response.BadReference(a.Logger, a.Name(), a.Oph.Name(), a.Oph.GetID(r), err)
	}

	var object T
	if err := json.NewDecoder(r.Body).Decode(&object); err != nil {
		a.Logger.Warn("Failed to decode object when creating", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Oph, r))
		return response.BadPayload(a.Logger, a.Name(), err)
	}

	if err := a.DB.Create(r.Context(), *account.GetID(), organizationRef, &object); err != nil {
		a.Logger.Warn("Error creating object", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Oph, r), mutil.PLog(a.Cph, r))
		return response.Auto(a.Logger, a.Name(), err)
	}

	if err := a.nconfig.CreateNotification(&object, *account.GetID()); err != nil {
		a.Logger.Warn("Failed to send creation notification", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Oph, r), mutil.PLog(a.Cph, r))
	}

	return a.ObjectCreated(&object, accessToken)
}
