package callbacksdb

import (
	"context"
	"strings"

	"github.com/tech/sendico/pkg/db/repository"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"go.mongodb.org/mongo-driver/v2/bson"
)

func (db *CallbacksDB) GetSigningSecretRef(ctx context.Context, accountRef, callbackRef bson.ObjectID) (string, error) {
	if callbackRef.IsZero() {
		return "", merrors.InvalidArgument("callback reference is required", "callbackRef")
	}

	// Enforce read permissions through the public callback object first.
	var callback model.Callback
	if err := db.Get(ctx, accountRef, callbackRef, &callback); err != nil {
		return "", err
	}

	internal := &callbackInternal{}
	if err := db.DBImp.Repository.Get(ctx, callbackRef, internal); err != nil {
		return "", err
	}

	return strings.TrimSpace(internal.SecretRef), nil
}

func (db *CallbacksDB) SetSigningSecretRef(ctx context.Context, accountRef, callbackRef bson.ObjectID, secretRef string) error {
	if callbackRef.IsZero() {
		return merrors.InvalidArgument("callback reference is required", "callbackRef")
	}
	value := strings.TrimSpace(secretRef)
	if value == "" {
		return merrors.InvalidArgument("secret reference is required", "secretRef")
	}

	return db.Patch(
		ctx,
		accountRef,
		callbackRef,
		repository.Patch().Set(repository.Field("secretRef"), value),
	)
}

func (db *CallbacksDB) ClearSigningSecretRef(ctx context.Context, accountRef, callbackRef bson.ObjectID) error {
	if callbackRef.IsZero() {
		return merrors.InvalidArgument("callback reference is required", "callbackRef")
	}

	return db.Patch(
		ctx,
		accountRef,
		callbackRef,
		repository.Patch().Unset(repository.Field("secretRef")),
	)
}
