package org.dromara.app.handler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.mqtt.MqttTopicHandler;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * 设备异常告警处理器 — 匹配 /{deviceNo}/publish/error
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ErromesHandler implements MqttTopicHandler {

    private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/error$");
    private final DeviceIdentityResolver deviceIdentityResolver;

    @Override
    public Pattern topicPattern() {
        return PATTERN;
    }

    @Override
    public void handle(String deviceIdentity, String payload) {
        String deviceNo = deviceIdentityResolver.resolveDeviceNo(deviceIdentity);
        try {
            if (deviceNo == null) {
                log.warn("[MQTT] 设备异常告警未找到设备 时间={} 设备标识={} 消息体={}",
                    HandlerLogTime.now(), deviceIdentity, payload);
                return;
            }
            Map<String, Object> dto = JsonUtils.parseObject(payload, Map.class);
            log.info("[MQTT] 设备异常告警 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, dto);
        } catch (Exception e) {
            log.error("[MQTT] 设备异常处理失败 时间={} 设备标识={} 设备编号={}",
                HandlerLogTime.now(), deviceIdentity, deviceNo, e);
        }
    }
}
