use std::error::Error;

use axum::Router;
use common::log;
use services::{granter, mdk_shield, registration_page, takumi_api};
use sqlx::PgPool;
use tracing::Level;

mod config;
mod database;
mod services;
mod util;

#[derive(Clone)]
pub struct SdkState {
    pub pg_pool: PgPool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    log::init_tracing();
    let span = tracing::span!(Level::DEBUG, "main");
    let _ = span.enter();

    let config = config::load().unwrap();

    let pg_pool = common::db::connect(&config.database.connection_string)
        .await
        .unwrap();

    let router = Router::new()
        .merge(takumi_api::make_routes())
        .merge(mdk_shield::make_routes())
        .merge(granter::make_routes())
        .merge(registration_page::make_routes())
        .with_state(SdkState { pg_pool });

    let server = axum_server::bind(config.bind_addr.parse()?);
    server.serve(router.into_make_service()).await?;

    Ok(())
}
