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.uber.org/zap"
)

func (a *ProtectedAPI[T]) archive(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)
	}
	organizationRef, err := a.Oph.GetRef(r)
	if err != nil {
		a.Logger.Warn("Failed to restore organization reference", zap.Error(err), mutil.PLog(a.Oph, r))
		return response.BadReference(a.Logger, a.Name(), a.Oph.Name(), a.Oph.GetID(r), err)
	}

	archived, err := mutil.GetArchiveParam(a.Logger, r)
	if err != nil {
		a.Logger.Warn("Failed to read optional 'archived' param", zap.Error(err))
		return response.Auto(a.Logger, a.resource, err)
	}
	if archived == nil {
		a.Logger.Warn("No archivation setting provided")
		return response.BadRequest(a.Logger, a.resource, "invalid_query_parameter", "'archived' pram must be present")
	}
	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)
	}
	if cascade == nil {
		a.Logger.Warn("Cascade property not specified, defaulting to false")
		csc := false
		cascade = &csc
	}

	ctx := r.Context()
	_, err = a.a.DBFactory().TransactionFactory().CreateTransaction().Execute(ctx, func(ctx context.Context) (any, error) {
		return nil, a.DB.SetArchived(ctx, *account.GetID(), organizationRef, objectRef, *archived, *cascade)
	})
	if err != nil {
		a.Logger.Warn("Failed to change archive property", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Cph, r),
			zap.Bool("archived", *archived), zap.Bool("cascade", *cascade))
		return response.Auto(a.Logger, a.Name(), err)
	}

	if a.nconfig.NeedArchiveNotification {
		var object T
		if err := a.DB.Get(ctx, *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 {
			if err := a.nconfig.ArchiveNotification(&object, *account.GetID()); err != nil {
				a.Logger.Warn("Failed to send archivation notification", zap.Error(err), mzap.StorableRef(account), mutil.PLog(a.Cph, r))
			}
		}
	}

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