package com.lingniu.ingest.inbound.mqtt.config;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

final class MqttInboundEnabledCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        Boolean direct = parseBoolean(env.getProperty("lingniu.ingest.mqtt.enabled"));
        if (direct != null) {
            return direct;
        }
        return isTrue(env.getProperty("YUTONG_MQTT_ENABLED"));
    }

    private static boolean isTrue(String value) {
        Boolean parsed = parseBoolean(value);
        return parsed != null && parsed;
    }

    private static Boolean parseBoolean(String value) {
        if (value == null || value.isBlank() || value.contains("${")) {
            return null;
        }
        String normalized = value.trim().toLowerCase();
        if ("true".equals(normalized) || "1".equals(normalized) || "yes".equals(normalized)
                || "on".equals(normalized)) {
            return true;
        }
        if ("false".equals(normalized) || "0".equals(normalized) || "no".equals(normalized)
                || "off".equals(normalized)) {
            return false;
        }
        return null;
    }
}
