package vassistent.model;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Unit tests for {@link AppState}.
 */
class AppStateTest {

    private AppState appState;

    /**
     * Creates a fresh app state instance for each test.
     */
    @BeforeEach
    void setUp() {
        appState = new AppState();
    }

    /**
     * Verifies problem level defaults to NONE.
     */
    @Test
    void defaultProblemLevel_isNone() {
        assertEquals(ProblemLevel.NONE, appState.getProblemLevel());
    }

    /**
     * Verifies MQTT status defaults to disconnected.
     */
    @Test
    void defaultMqttState_isDisconnected() {
        assertFalse(appState.isMqttConnected());
    }

    /**
     * Verifies listeners are notified when problem level changes.
     */
    @Test
    void setProblemLevel_notifiesListeners() {
        AtomicInteger notifications = new AtomicInteger(0);
        appState.addListener(state -> notifications.incrementAndGet());

        appState.setProblemLevel(ProblemLevel.HIGH);

        assertEquals(1, notifications.get());
        assertEquals(ProblemLevel.HIGH, appState.getProblemLevel());
    }

    /**
     * Verifies MQTT listener notifications happen only when value changes.
     */
    @Test
    void setMqttConnected_notifiesOnlyOnChange() {
        AtomicInteger notifications = new AtomicInteger(0);
        appState.addListener(state -> notifications.incrementAndGet());

        appState.setMqttConnected(true);
        appState.setMqttConnected(true);
        appState.setMqttConnected(false);

        assertEquals(2, notifications.get());
        assertFalse(appState.isMqttConnected());
    }

    /**
     * Verifies setting MQTT state to true updates the state value.
     */
    @Test
    void setMqttConnected_updatesValue() {
        appState.setMqttConnected(true);

        assertTrue(appState.isMqttConnected());
    }
}
