use sqlx::PgPool;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod database;
mod html;
mod macros;

pub async fn run() -> std::io::Result<()> {
    let pool: PgPool = match database::establish_connection().await {
        Ok(p) => p,
        Err(_) => panic!("error connecting to database"),
    };
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "achubb_backend".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
    info!("initializing router...");
    let port = 21212_u16;
    let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port));
    let router = html::root::get_router(pool);
    info!("router initialized, now listening on port {}", port);
    match axum::Server::bind(&addr)
        .serve(router.into_make_service())
        .await
    {
        Ok(p) => p,
        Err(_) => panic!("error starting webserver"),
    }
    Ok(())
}
