package com.cmvr.quic.gateway;

import com.cmvr.quic.gateway.config.GatewayConfig;
import com.cmvr.quic.gateway.core.NodeEventBroker;
import com.cmvr.quic.gateway.server.QuicGatewayServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/** 在 CMVR Spring 应用生命周期内运行 QUIC 接入服务。 */
@Component
@ConditionalOnProperty(prefix = "cmvr.quic", name = "enabled", havingValue = "true")
public final class IntegratedQuicGatewayLifecycle implements SmartLifecycle {

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

    private final Environment environment;
    private final NodeEventBroker broker;
    private final AtomicBoolean running = new AtomicBoolean(false);
    private QuicGatewayServer quicServer;

    public IntegratedQuicGatewayLifecycle(Environment environment, NodeEventBroker broker) {
        this.environment = environment;
        this.broker = broker;
    }

    @Override
    public void start() {
        if (!running.compareAndSet(false, true)) {
            return;
        }
        try {
            GatewayConfig config = GatewayConfig.load(environment);
            quicServer = new QuicGatewayServer(config, broker);
            quicServer.start();
            log.info("集成式 QUIC Gateway 已随 CMVR 应用启动");
        } catch (Exception error) {
            stopComponents();
            running.set(false);
            throw new IllegalStateException("集成式 QUIC Gateway 启动失败", error);
        }
    }

    @Override
    public void stop() {
        if (!running.compareAndSet(true, false)) {
            return;
        }
        stopComponents();
        log.info("集成式 QUIC Gateway 已停止");
    }

    private void stopComponents() {
        if (quicServer != null) {
            quicServer.close();
            quicServer = null;
        }
    }

    @Override
    public boolean isRunning() {
        return running.get();
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE - 100;
    }
}

