package org.raddatz.familienarchiv.auth;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.session.jdbc.JdbcIndexedSessionRepository;

import java.util.HashMap;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class JdbcSessionRevocationAdapterTest {

    @Mock JdbcIndexedSessionRepository sessionRepository;
    @InjectMocks JdbcSessionRevocationAdapter adapter;

    @SuppressWarnings("unchecked")
    @Test
    void revokeOtherSessions_preserves_current_and_deletes_N_minus_1() {
        var sessions = new HashMap<String, Object>();
        sessions.put("session-keep", null);
        sessions.put("session-del-1", null);
        sessions.put("session-del-2", null);
        doReturn(sessions).when(sessionRepository).findByPrincipalName("user@test.de");

        int count = adapter.revokeOtherSessions("session-keep", "user@test.de");

        assertThat(count).isEqualTo(2);
        verify(sessionRepository, never()).deleteById("session-keep");
        verify(sessionRepository).deleteById("session-del-1");
        verify(sessionRepository).deleteById("session-del-2");
    }

    @SuppressWarnings("unchecked")
    @Test
    void revokeAllSessions_deletes_all_sessions_for_principal() {
        var sessions = new HashMap<String, Object>();
        sessions.put("session-1", null);
        sessions.put("session-2", null);
        doReturn(sessions).when(sessionRepository).findByPrincipalName("user@test.de");

        int count = adapter.revokeAllSessions("user@test.de");

        assertThat(count).isEqualTo(2);
        verify(sessionRepository).deleteById("session-1");
        verify(sessionRepository).deleteById("session-2");
    }
}
