package at.procon.eventhub.tachographfilesession.service;

import at.procon.eventhub.config.EventHubProperties;
import at.procon.eventhub.tachographfilesession.model.TachographFileSession;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Repository;

@Repository
public class InMemoryTachographFileSessionRepository implements TachographFileSessionRepository {

    private final ConcurrentHashMap<UUID, TachographFileSession> sessions = new ConcurrentHashMap<>();
    private final EventHubProperties properties;

    public InMemoryTachographFileSessionRepository(EventHubProperties properties) {
        this.properties = properties;
    }

    @Override
    public TachographFileSession save(TachographFileSession session) {
        cleanupExpired();
        if (!sessions.containsKey(session.sessionId())
                && sessions.size() >= properties.getTachographFileSession().getMaxSessions()) {
            throw new IllegalStateException("Maximum number of tachograph file sessions reached.");
        }
        sessions.put(session.sessionId(), session);
        return session;
    }

    @Override
    public Optional<TachographFileSession> find(UUID sessionId) {
        cleanupExpired();
        return Optional.ofNullable(sessions.get(sessionId));
    }

    @Override
    public boolean delete(UUID sessionId) {
        cleanupExpired();
        return sessions.remove(sessionId) != null;
    }

    @Override
    public List<TachographFileSession> list() {
        cleanupExpired();
        return List.copyOf(sessions.values());
    }

    private void cleanupExpired() {
        Instant now = Instant.now();
        sessions.entrySet().removeIf(entry -> entry.getValue().expiresAt() != null && entry.getValue().expiresAt().isBefore(now));
    }
}
