package org.dromara.app.handler;

import lombok.extern.slf4j.Slf4j;
import org.dromara.app.mqtt.MqttTopicHandler;
import org.dromara.app.service.IDeviceCommandAckHandler;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 设备命令 ACK 处理器 — 匹配 /{deviceNo}/publish/ack。
 * 委托给 {@link IDeviceCommandAckHandler}（实际由 water-common-mqtt 模块的 MqttCommandAckService 实现）。
 */
@Slf4j
@Component
public class DeviceCommandAckHandler implements MqttTopicHandler {

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

    private final IDeviceCommandAckHandler delegate;
    private final DeviceIdentityResolver deviceIdentityResolver;

    public DeviceCommandAckHandler(IDeviceCommandAckHandler delegate, DeviceIdentityResolver deviceIdentityResolver) {
        this.delegate = delegate;
        this.deviceIdentityResolver = deviceIdentityResolver;
    }

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

    @Override
    public void handle(String deviceIdentity, String payload) {
        String deviceNo = deviceIdentityResolver.resolveDeviceNo(deviceIdentity);
        if (deviceNo == null) {
            log.warn("[MQTT] ACK 未找到设备 设备标识={} 消息体={}", deviceIdentity, payload);
            return;
        }
        delegate.handleAck(deviceNo, payload);
    }
}
