package dev.lions.user.manager.client.view;

import dev.lions.faces.layout.view.GuestPreferences;
import dev.lions.faces.layout.view.UserSessionBean;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class SettingsBeanTest {

    @Mock
    UserSessionBean userSessionBean;

    @Mock
    GuestPreferences guestPreferences;

    @Mock
    FacesContext facesContext;

    @InjectMocks
    SettingsBean settingsBean;

    MockedStatic<FacesContext> facesContextMock;

    @BeforeEach
    void setUp() {
        facesContextMock = mockStatic(FacesContext.class);
        facesContextMock.when(FacesContext::getCurrentInstance).thenReturn(facesContext);
    }

    @AfterEach
    void tearDown() {
        if (facesContextMock != null) {
            facesContextMock.close();
        }
    }

    @Test
    void testInit() {
        settingsBean.init();
        // Vérifier que l'initialisation se fait sans erreur
        assertNotNull(settingsBean);
    }

    @Test
    void testSavePreferences() {
        settingsBean.savePreferences();

        verify(facesContext).addMessage(isNull(), any(FacesMessage.class));
    }

    @Test
    void testSavePreferencesError() {
        // Simuler une erreur lors de l'accès à FacesContext
        facesContextMock.when(FacesContext::getCurrentInstance).thenThrow(new RuntimeException("Error"));

        // Le bean devrait gérer l'erreur gracieusement
        assertDoesNotThrow(() -> {
            try {
                settingsBean.savePreferences();
            } catch (Exception e) {
                // L'erreur est attendue dans ce cas
            }
        });
    }
}

