package signature

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

type NonceStore interface {
	SetIfNotExists(ctx context.Context, appId, nonce string, ttlSeconds int64) (bool, error)
}

type RedisNonceStore struct {
	client *redis.Client
}

func NewRedisNonceStore(client *redis.Client) *RedisNonceStore {
	return &RedisNonceStore{client: client}
}

func (s *RedisNonceStore) SetIfNotExists(ctx context.Context, appId, nonce string, ttlSeconds int64) (bool, error) {
	key := fmt.Sprintf("sig:nonce:%s:%s", appId, nonce)
	ok, err := s.client.SetNX(ctx, key, "1", time.Duration(ttlSeconds)*time.Second).Result()
	if err != nil {
		return false, err
	}
	return !ok, nil
}
