package callbacksimp

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/server/interface/api/sresponse"
	"go.uber.org/zap"
)

func (a *CallbacksAPI) update(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	var input model.Callback
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		a.Logger.Warn("Failed to decode callback payload", zap.Error(err))
		return response.BadPayload(a.Logger, a.Name(), err)
	}

	callbackRef := *input.GetID()
	if callbackRef.IsZero() {
		return response.Auto(a.Logger, a.Name(), merrors.InvalidArgument("callback ref is required", "id"))
	}

	var existing model.Callback
	if err := a.db.Get(r.Context(), *account.GetID(), callbackRef, &existing); err != nil {
		a.Logger.Warn("Failed to fetch callback before update", zap.Error(err))
		return response.Auto(a.Logger, a.Name(), err)
	}
	existingSecretRef, err := a.db.GetSigningSecretRef(r.Context(), *account.GetID(), callbackRef)
	if err != nil && !errors.Is(err, merrors.ErrNoData) {
		a.Logger.Warn("Failed to fetch callback signing secret metadata", zap.Error(err))
		return response.Auto(a.Logger, a.Name(), err)
	}

	mergeCallbackMutable(&existing, &input)
	mutation, err := a.normalizeAndPrepare(r.Context(), &existing, existing.OrganizationRef, existingSecretRef, true)
	if err != nil {
		return response.Auto(a.Logger, a.Name(), err)
	}

	if _, err := a.tf.CreateTransaction().Execute(r.Context(), func(ctx context.Context) (any, error) {
		if err := a.DB.Update(ctx, *account.GetID(), &existing); err != nil {
			return nil, err
		}
		if err := a.applySigningSecretMutation(ctx, *account.GetID(), callbackRef, mutation); err != nil {
			return nil, err
		}
		return struct{}{}, nil
	}); err != nil {
		a.Logger.Warn("Failed to update callback transaction", zap.Error(err))
		return response.Auto(a.Logger, a.Name(), err)
	}

	return a.callbackResponse(&existing, accessToken, mutation.Generated, false)
}
