use std::sync::Arc;

use infra::core::{AppState, config::config};
use tokio::signal::unix::{SignalKind, signal};

use crate::router;

pub async fn run(state: Arc<AppState>) {
    let addr = config().get_string("app.addr").unwrap();

    let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();

    tracing::info!("listening on {}", addr);

    axum::serve(listener, router::init().with_state(state))
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
}

async fn shutdown_signal() {
    let mut sigint = signal(SignalKind::interrupt()).unwrap();
    let mut sigquit = signal(SignalKind::quit()).unwrap();
    let mut sigterm = signal(SignalKind::terminate()).unwrap();

    tokio::select! {
        _ = sigint.recv() => {
            println!("收到 SIGINT 信号，正在关闭服务...");
        }
        _ = sigquit.recv() => {
            println!("收到 SIGQUIT 信号，正在关闭服务...");
        }
        _ = sigterm.recv() => {
            println!("收到 SIGTERM 信号，正在关闭服务...");
        }
    }
}
