package com.usky.cdi.service.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.cdi.domain.CdiDefenseProject;
import com.usky.cdi.mapper.CdiDefenseProjectMapper;
import com.usky.cdi.service.config.Gb28181VideoProperties;
import com.usky.common.core.exception.BusinessException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 解析 GB28181 视频 MQTT 凭据：优先读 yml，缺失时从人防工程表补全。
 */
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "gb28181.video", name = "enabled", havingValue = "true")
public class Gb28181MqttCredentialResolver {

    private final Gb28181VideoProperties properties;
    private final CdiDefenseProjectMapper cdiDefenseProjectMapper;

    public MqttCredentials resolve() {
        Integer tenantId = properties.getTenantId();
        Long engineeringId = properties.getEngineeringId();
        String username = properties.getMqttUsername();
        String password = properties.getMqttPassword();

        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)
                || tenantId == null || engineeringId == null) {
            CdiDefenseProject project = lookupDefenseProject(tenantId, engineeringId);
            if (project != null) {
                if (tenantId == null) {
                    tenantId = project.getTenantId();
                }
                if (engineeringId == null) {
                    engineeringId = project.getEngineeringId();
                }
                if (!StringUtils.hasText(username)) {
                    username = project.getMqttUserName();
                }
                if (!StringUtils.hasText(password)) {
                    password = project.getMqttPassword();
                }
            }
        }

        if (engineeringId == null) {
            throw new BusinessException("未配置 gb28181.video.engineering-id");
        }
        if (tenantId == null) {
            throw new BusinessException("未配置 gb28181.video.tenant-id");
        }
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new BusinessException(
                    "未配置 gb28181.video.mqtt-username / mqtt-password，且人防工程表(cdi_defense_project)中未找到有效凭据");
        }
        return new MqttCredentials(username, password, tenantId, engineeringId);
    }

    private CdiDefenseProject lookupDefenseProject(Integer tenantId, Long engineeringId) {
        LambdaQueryWrapper<CdiDefenseProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CdiDefenseProject::getIsEnable, 1);
        if (engineeringId != null) {
            queryWrapper.eq(CdiDefenseProject::getEngineeringId, engineeringId);
        }
        if (tenantId != null) {
            queryWrapper.eq(CdiDefenseProject::getTenantId, tenantId);
        }
        return cdiDefenseProjectMapper.selectOne(queryWrapper);
    }

    @Getter
    @RequiredArgsConstructor
    public static class MqttCredentials {
        private final String username;
        private final String password;
        private final Integer tenantId;
        private final Long engineeringId;
    }
}
