package com.ttstd.signaling.store;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** 内存 nonce 去重实现，用于 storage.mode=memory 或 Redis 不可用时的降级。 */
@Component
@Profile("memory")
public class InMemoryNonceStore implements NonceStore {

    private final Map<String, Instant> nonces = new ConcurrentHashMap<>();

    @Override
    public synchronized boolean tryReserve(String nonce, long ttlSeconds) {
        Instant now = Instant.now();
        nonces.entrySet().removeIf(e -> now.isAfter(e.getValue()));
        if (nonces.containsKey(nonce)) {
            return false;
        }
        nonces.put(nonce, now.plusSeconds(ttlSeconds));
        return true;
    }
}
