package papitemplate

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

func (a *ProtectedAPI[T]) deleteImp(ctx context.Context, account *model.Account, objectRef bson.ObjectID, cascade *bool) error {
	var err error
	if (cascade != nil) && (*cascade) {
		_, err = a.a.DBFactory().TransactionFactory().CreateTransaction().Execute(ctx, func(ctx context.Context) (any, error) {
			return nil, a.DB.DeleteCascadeAuth(ctx, *account.GetID(), objectRef)
		})
	} else {
		err = a.DB.Delete(ctx, *account.GetID(), objectRef)
	}
	if err != nil {
		a.Logger.Warn("Error deleting object", zap.Error(err), mzap.StorableRef(account), mzap.ObjRef("object_ref", objectRef))
		return err
	}
	return nil
}

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

	cascade, err := mutil.GetCascadeParam(a.Logger, r)
	if err != nil {
		a.Logger.Warn("Failed to read optional 'cascade' param", zap.Error(err))
		return response.Auto(a.Logger, a.resource, err)
	}

	var objPtr *T
	if a.nconfig.NeedDeleteNotification {
		var object T
		if err := a.DB.Get(r.Context(), *account.GetID(), objectRef, &object); err != nil {
			a.Logger.Warn("Failed to fetch object for notification", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Cph, r))
		} else {
			objPtr = &object
		}
	}

	if err := a.deleteImp(r.Context(), account, objectRef, cascade); err != nil {
		a.Logger.Warn("Error deleting object", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Cph, r))
		return response.Auto(a.Logger, a.Name(), err)
	}

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

	return a.Objects([]T{}, accessToken)
}
