mod api_keys;
mod app_error;
mod app_state;
mod auth;
mod csrf;
mod models;
mod projects;
mod router;
mod schema;
mod sessions;
mod settings;
mod users;

use app_state::AppState;
use router::new_router;
use sessions::PgStore;
use tracing_subscriber::EnvFilter;

use crate::settings::Settings;

#[tokio::main]
async fn main() {
    let settings = Settings::load().unwrap();

    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let database_url = settings.database_url.clone();
    let manager =
        deadpool_diesel::postgres::Manager::new(database_url, deadpool_diesel::Runtime::Tokio1);
    let db_pool = deadpool_diesel::postgres::Pool::builder(manager)
        .build()
        .unwrap();

    let session_store = PgStore::new(db_pool.clone());

    let oauth_client = auth::new_oauth_client(&settings).unwrap();
    let app_state = AppState {
        db_pool,
        oauth_client,
        session_store,
        settings: settings.clone(),
    };

    let router = new_router(app_state);

    let listener = tokio::net::TcpListener::bind((settings.host, settings.port))
        .await
        .unwrap();
    axum::serve(listener, router).await.unwrap();
}
