package com.usky.cdi.service.sip.service;

import com.usky.cdi.service.sip.config.SipServerProperties;
import com.usky.cdi.service.sip.listener.SipServerListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;

@Slf4j
@Service
@ConditionalOnProperty(prefix = "sip.server", name = "enabled", havingValue = "true")
public class SipServerService {

    private final SipServerProperties properties;
    private final SipServerListener sipServerListener;

    public SipServerService(SipServerProperties properties, SipServerListener sipServerListener) {
        this.properties = properties;
        this.sipServerListener = sipServerListener;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        if (!properties.isEnabled()) {
            log.info("SIP 服务端未启用 (sip.server.enabled=false)");
            return;
        }
        try {
            sipServerListener.start();
        } catch (Exception e) {
            log.error("SIP 服务端启动失败: {}", e.getMessage(), e);
        }
    }

    @PreDestroy
    public void shutdown() {
        sipServerListener.stop();
    }
}
