//! SMTP TCP 监听与连接派发。

use crate::smtp::session;
use crate::AppState;
use tokio::net::TcpListener;

pub async fn run(state: AppState) -> anyhow::Result<()> {
    let addr = format!(
        "{}:{}",
        state.config.smtp.listen_host, state.config.smtp.listen_port
    );
    let listener = TcpListener::bind(&addr).await?;
    state.runtime_health.smtp_healthy(addr.clone()).await;
    tracing::info!(%addr, "SMTP 服务器监听中");
    loop {
        let (stream, peer) = listener.accept().await?;
        let state = state.clone();
        let timeout_secs = state.config.smtp.connection_timeout_seconds;
        tokio::spawn(async move {
            let result = tokio::time::timeout(
                std::time::Duration::from_secs(timeout_secs),
                session::run_session(stream, peer, state),
            )
            .await;
            match result {
                Ok(Ok(())) => {}
                Ok(Err(e)) => tracing::warn!(?peer, %e, "SMTP 会话错误"),
                Err(_) => tracing::warn!(?peer, "SMTP 会话超时"),
            }
        });
    }
}
