use clap::Parser as _;
use diesel_migrations::MigrationHarness;
use dotenvy::dotenv;
use tracing_subscriber::EnvFilter;

use crate::{
    app_state::{App, AppState},
    cli::{serve_command, worker_command, Cli, Commands},
    migrations::MIGRATIONS,
    settings::Settings,
};

mod api_keys;
mod app_error;
mod app_state;
mod auth;
mod channel_selections;
mod channels;
mod channels_router;
mod cli;
mod csrf;
mod email;
mod governors;
mod guards;
mod messages;
mod middleware;
mod migrations;
mod nav;
mod projects;
mod projects_router;
mod router;
mod schema;
mod sessions;
mod settings;
mod team_memberships;
mod teams;
mod teams_router;
mod users;
mod v0_router;
mod worker;

/// Run CLI
#[tokio::main]
async fn main() {
    // Attempt to pre-load .env in case it contains a RUST_LOG variable
    dotenv().ok();
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let settings = Settings::load().unwrap();

    let state: AppState = App::from_settings(settings.clone()).await.unwrap().into();

    if settings.run_database_migrations == Some(1) {
        // Run migrations on server startup
        let conn = state.db_pool.get().await.unwrap();
        conn.interact(|conn| conn.run_pending_migrations(MIGRATIONS).map(|_| ()))
            .await
            .unwrap()
            .unwrap();
    }

    let cli = Cli::parse();
    match &cli.command {
        Commands::Serve => serve_command(state).await.unwrap(),
        Commands::Worker(args) => worker_command(args, state).await.unwrap(),
    }
}
