package de.assecutor.votianlt.service;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.stereotype.Service;

@Service
public class DemoSessionRegistry {

    private final AtomicReference<String> activeSessionId = new AtomicReference<>();

    public synchronized boolean acquire(String sessionId) {
        if (sessionId == null || sessionId.isBlank()) {
            return false;
        }

        String current = activeSessionId.get();
        if (current == null || Objects.equals(current, sessionId)) {
            activeSessionId.set(sessionId);
            return true;
        }

        return false;
    }

    public boolean isHeldBy(String sessionId) {
        return sessionId != null && sessionId.equals(activeSessionId.get());
    }

    public synchronized void release(String sessionId) {
        if (isHeldBy(sessionId)) {
            activeSessionId.set(null);
        }
    }

    public Optional<String> getActiveSessionId() {
        return Optional.ofNullable(activeSessionId.get());
    }
}
