package callbacksimp

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

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

func (a *CallbacksAPI) 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 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)
	}

	var callback model.Callback
	if err := json.NewDecoder(r.Body).Decode(&callback); err != nil {
		a.Logger.Warn("Failed to decode callback payload", zap.Error(err))
		return response.BadPayload(a.Logger, a.Name(), err)
	}

	mutation, err := a.normalizeAndPrepare(r.Context(), &callback, organizationRef, "", 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.Create(ctx, *account.GetID(), organizationRef, &callback); err != nil {
			return nil, err
		}
		if err := a.applySigningSecretMutation(ctx, *account.GetID(), *callback.GetID(), mutation); err != nil {
			return nil, err
		}
		return struct{}{}, nil
	}); err != nil {
		a.Logger.Warn("Failed to create callback transaction", zap.Error(err))
		return response.Auto(a.Logger, a.Name(), err)
	}

	return a.callbackResponse(&callback, accessToken, mutation.Generated, true)
}
