package com.usky.vpp.job;

import com.usky.vpp.config.VppUnProperties;
import com.usky.vpp.service.VppUnIntegrationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 启动时自动向 UN 注册（可选）
 */
@Component
@ConditionalOnProperty(name = "vpp.un.auto-register-on-startup", havingValue = "true")
public class VppUnBootstrapRunner implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(VppUnBootstrapRunner.class);

    @Autowired
    private VppUnProperties properties;

    @Autowired
    private VppUnIntegrationService integrationService;

    @Override
    public void run(ApplicationArguments args) {
        if (!properties.isOutboundActive()) {
            log.warn("auto-register-on-startup 已开启但 outbound 未激活，跳过");
            return;
        }
        try {
            integrationService.refreshToken();
            if (!StringUtils.hasText(properties.getRegistrationId())) {
                integrationService.register();
                log.info("启动注册 UN 完成");
            } else {
                log.info("已有 registrationID={}，跳过启动注册", properties.getRegistrationId());
            }
        } catch (Exception ex) {
            log.warn("启动注册 UN 失败: {}", ex.getMessage());
        }
    }
}
