package org.raddatz.familienarchiv.auth;

import lombok.RequiredArgsConstructor;
import org.springframework.session.jdbc.JdbcIndexedSessionRepository;

@RequiredArgsConstructor
class JdbcSessionRevocationAdapter implements SessionRevocationPort {

    private final JdbcIndexedSessionRepository sessionRepository;

    @Override
    public int revokeOtherSessions(String currentSessionId, String principalName) {
        int count = 0;
        for (String id : sessionRepository.findByPrincipalName(principalName).keySet()) {
            if (!id.equals(currentSessionId)) {
                sessionRepository.deleteById(id);
                count++;
            }
        }
        return count;
    }

    @Override
    public int revokeAllSessions(String principalName) {
        var sessions = sessionRepository.findByPrincipalName(principalName);
        sessions.keySet().forEach(sessionRepository::deleteById);
        return sessions.size();
    }
}
