use tower_http::services::{ServeDir, ServeFile};
use tower_http::trace::TraceLayer;
use tracing_subscriber::EnvFilter;

use photos::config::Config;
use photos::state::AppState;

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

    let config = Config::from_env()?;
    let state = AppState::new(config).await?;

    let static_dir = state.config.static_dir.clone();
    let index = std::path::Path::new(&static_dir).join("index.html");
    // .fallback (not .not_found_service) so SPA routes get index.html with a 200
    let spa = ServeDir::new(&static_dir).fallback(ServeFile::new(index));

    let app = photos::routes::router(&state)
        .fallback_service(spa)
        .layer(TraceLayer::new_for_http())
        .with_state(state.clone());

    let listener = tokio::net::TcpListener::bind(&state.config.bind_addr).await?;
    tracing::info!("listening on http://{}", state.config.bind_addr);
    axum::serve(listener, app).await?;
    Ok(())
}
