use std::{error::Error, net::SocketAddr};

use axum::Router;
use axum_cms_raw::apps::main_app::main_app;
use axum_cms_raw::database::db::Db;
use tokio::net::TcpListener;
use tower_cookies::CookieManagerLayer;
use tracing::info;
use tracing::subscriber::set_global_default;
use tracing_subscriber::fmt::format::FmtSpan;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let subscriber = tracing_subscriber::fmt()
        .with_file(true)
        .with_line_number(true)
        .with_max_level(tracing::Level::TRACE)
        .with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
        .finish();

    set_global_default(subscriber).expect("Setting Subsciber not successful");

    let addr = SocketAddr::from(([127, 0, 0, 1], 4000));
    let listener = TcpListener::bind(addr).await?;
    let router = Router::new();

    let verification_endpoint =
        "http://localhost:3000/cms-pages/verify?verification_id=".to_owned();
    let db = Db::new()?;

    db.init()?;

    let main_app = main_app(db, verification_endpoint)?;
    let router = router.merge(main_app).layer(CookieManagerLayer::new());

    info!("Running Server on {:?}", listener.local_addr());

    axum::serve(listener, router).await?;

    Ok(())
}
