#![allow(async_fn_in_trait)]
use crate::database::article::load_articles;
use database::link::load_links;
use sqlx::PgPool;
use std::error::Error;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

pub mod database;
mod html;
mod macros;

pub async fn run_server(pool: PgPool) -> std::io::Result<()> {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "achubb_website".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(())
}

pub async fn run_load(pool: &PgPool) -> Result<(), Box<dyn Error>> {
    load_articles(pool).await?;
    load_links(pool).await?;
    Ok(())
}
