package com.usky.vpp.service.impl;

import com.usky.vpp.config.VppUnProperties;
import com.usky.vpp.config.VppUnPropertiesRegistry;
import com.usky.vpp.config.VppUnTenantContext;
import com.usky.vpp.service.VppUnIntegrationService;
import com.usky.vpp.service.VppUnPollTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VppUnPollTaskServiceImpl implements VppUnPollTaskService {

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

    @Autowired
    private VppUnPropertiesRegistry propertiesRegistry;

    @Autowired
    private VppUnIntegrationService integrationService;

    @Override
    public void pollUn(Integer tenantId) {
        log.info("pollUn start, tenantId={}", tenantId);
        VppUnProperties properties = propertiesRegistry.get(tenantId);
        if (properties == null) {
            log.warn("pollUn skipped: tenantId={} 未配置运管平台 UN 对接信息", tenantId);
            return;
        }
        if (!properties.isPollActive()) {
            log.info("pollUn skipped: poll not active, tenantId={}", tenantId);
            return;
        }
        VppUnTenantContext.runWithTenant(tenantId, () -> {
            try {
                integrationService.pollOnce();
            } catch (Exception ex) {
                log.warn("UN Poll 失败, tenantId={}: {}", tenantId, ex.getMessage());
            }
        });
    }
}
