package org.dromara.app.handler;

import lombok.RequiredArgsConstructor;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.mapper.AppDeviceMapper;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 解析 MQTT Topic 中的设备标识。
 * <p>
 * Topic 第一段允许传设备编号或 MAC 地址。业务处理统一转换为数据库中的设备编号。
 */
@Component
@RequiredArgsConstructor
public class DeviceIdentityResolver {

    private final AppDeviceMapper appDeviceMapper;

    public AppDevice resolve(String identity) {
        if (StringUtils.isBlank(identity)) {
            return null;
        }
        String text = identity.trim();
        AppDevice device = appDeviceMapper.selectById(text);
        if (device != null) {
            return device;
        }
        return appDeviceMapper.selectByMac(normalizeMacAddress(text));
    }

    public String resolveDeviceNo(String identity) {
        AppDevice device = resolve(identity);
        return device == null ? null : device.getDeviceNo();
    }

    public String normalizeMacAddress(String macAddress) {
        if (StringUtils.isBlank(macAddress)) {
            return null;
        }
        return macAddress.trim().toLowerCase(Locale.ROOT);
    }
}
