pub mod router;
pub mod util;
use crate::{
    configuration::CONFIGURATION,
    db::{self, DB_POOL},
};
use log::info;
use router::*;
use util::*;

pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
    // initialize database
    let app = create_router().unwrap();
    let config = CONFIGURATION.get().unwrap();
    let db_pool =
        db::DbConnectionPool::new(&config.db.connection_string(), config.db.max_connections);
    let addr = format!("{}:{}", config.server.host, config.server.port);

    db_pool
        .run_migrations()
        .expect("Failed to run database migrations");

    DB_POOL
        .set(db_pool)
        .expect("Failed to set database connection pool");

    info!("Database connection pool initialized");

    let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
    info!("NoManSky server listening on {}", &addr);
    axum::serve(listener, app).await.unwrap();
    info!("NoManSky server listening stopped");
    Ok(())
}
