package org.dromara.web.config;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

@Tag("dev")
class MqttCommandAckConfigUnitTest {

    @Test
    void commandAckRetrySettingsMatchRuntimeRequirements() throws Exception {
        Map<?, ?> commandAckConfig = null;
        Yaml yaml = new Yaml();
        try (InputStream inputStream = new ClassPathResource("application.yml").getInputStream()) {
            for (Object document : yaml.loadAll(inputStream)) {
                if (!(document instanceof Map<?, ?> root)) {
                    continue;
                }
                Object mqtt = root.get("mqtt");
                if (!(mqtt instanceof Map<?, ?> mqttConfig)) {
                    continue;
                }
                Object commandAck = mqttConfig.get("command-ack");
                if (commandAck instanceof Map<?, ?> config) {
                    commandAckConfig = config;
                }
            }
        }

        assertThat(commandAckConfig).isNotNull();
        assertThat(commandAckConfig.get("retry-interval-ms")).isEqualTo(10000);
        assertThat(commandAckConfig.get("scan-interval-ms")).isEqualTo(5000);
        assertThat(commandAckConfig.get("max-retry-count")).isEqualTo(3);
    }

    @Test
    void offlineCheckTtlCompatibilityIsEnabled() throws Exception {
        Boolean ttlCompatEnabled = null;
        Yaml yaml = new Yaml();
        try (InputStream inputStream = new ClassPathResource("application.yml").getInputStream()) {
            for (Object document : yaml.loadAll(inputStream)) {
                if (!(document instanceof Map<?, ?> root)) {
                    continue;
                }
                Object mqtt = root.get("mqtt");
                if (!(mqtt instanceof Map<?, ?> mqttConfig)) {
                    continue;
                }
                Object offlineCheck = mqttConfig.get("offline-check");
                if (offlineCheck instanceof Map<?, ?> offlineCheckConfig) {
                    ttlCompatEnabled = (Boolean) offlineCheckConfig.get("ttl-compat-enabled");
                }
            }
        }

        assertThat(ttlCompatEnabled).isTrue();
    }
}
