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

func (a *AccountAPI[T]) deleteImp(ctx context.Context, account *model.Account, objectRef bson.ObjectID) error {
	if err := a.DB.Delete(ctx, *account.GetID(), objectRef); 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 *AccountAPI[T]) delete(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	objectRef, err := a.Oph.GetRef(r)
	if err != nil {
		a.Logger.Warn("Failed to restore 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 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.Oph, r))
		} else {
			objPtr = &object
		}
	}

	if err := a.deleteImp(r.Context(), account, objectRef); err != nil {
		a.Logger.Warn("Error deleting object", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Oph, 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.Oph, r))
		}
	}

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