use std::sync::Arc;
use tracing::info;

use dd0c_route::{AppConfig, LocalAuthProvider};

mod handler;
use handler::{create_api_router, ApiState};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "dd0c_route=info,tower_http=info".into()),
        )
        .json()
        .init();

    let config = Arc::new(AppConfig::from_env()?);
    info!(port = config.api_port, "Starting dd0c/route Dashboard API");

    let pg_pool = sqlx::PgPool::connect(&config.database_url).await?;
    let ts_pool = sqlx::PgPool::connect(&config.timescale_url).await?;
    let redis_cfg = deadpool_redis::Config::from_url(&config.redis_url);
    let redis_pool = redis_cfg.create_pool(Some(deadpool_redis::Runtime::Tokio1))?;

    let state = Arc::new(ApiState {
        auth: Arc::new(LocalAuthProvider::new(
            pg_pool.clone(),
            config.jwt_secret.clone(),
            redis_pool,
        )),
        pg_pool,
        ts_pool,
        config: config.clone(),
    });

    let app = create_api_router(state);
    let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", config.api_port)).await?;
    info!(port = config.api_port, "Dashboard API listening");
    axum::serve(listener, app).await?;

    Ok(())
}
