package com.usky.vpp.job;

import com.usky.vpp.config.VppUnProperties;
import com.usky.vpp.config.VppUnPropertiesRegistry;
import com.usky.vpp.service.VppUnRegisterTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 服务启动时从 vpp_tenant_config 加载 UN 配置至内存，并按需自动注册 UN
 */
@Component
@Order(100)
public class VppUnPropertiesLoader implements ApplicationRunner {

    @Autowired
    private VppUnPropertiesRegistry propertiesRegistry;

    @Autowired
    private VppUnRegisterTaskService unRegisterTaskService;

    @Override
    public void run(ApplicationArguments args) {
        propertiesRegistry.refreshAll();
        autoRegisterOnStartup();
    }

    private void autoRegisterOnStartup() {
        for (VppUnProperties properties : propertiesRegistry.getAll()) {
            if (!Boolean.TRUE.equals(properties.getAutoRegisterOnStartup()) || !properties.isOutboundActive()) {
                continue;
            }
            unRegisterTaskService.registerUn(properties.getTenantId());
        }
    }
}
