use std::env;
use tower_http::set_header::SetResponseHeaderLayer;
use axum::http::header;
use axum::{
    http::HeaderValue,
    http::HeaderName,
    response::IntoResponse,
    routing::get,
    Router,
};
use tower::ServiceBuilder;

#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
    use axum::Router;
    use leptos::logging::log;
    use leptos::prelude::*;
    use leptos_axum::{generate_route_list, LeptosRoutes};
    use vproxy_web::app::*;
    use vproxy_web::i18n::preload_all_translations;

    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
        .target(env_logger::Target::Stdout)
        .format_timestamp_secs()
        .init();

    dotenv::dotenv().ok();

    log::info!("BACKEND_URL: {}", env::var("BACKEND_URL").unwrap());
    log::info!("BACKEND_USERNAME: {}", env::var("BACKEND_USERNAME").unwrap());
    log::info!("BACKEND_PASSWORD: {}", env::var("BACKEND_PASSWORD").unwrap());

    log::info!("Starting VProxy Web Server...");

    log::info!("Preloading translations...");
    if let Err(e) = preload_all_translations().await {
        log::error!("Failed to preload translations: {}", e);
        std::process::exit(1);
    }

    let conf = get_configuration(None).unwrap();
    let addr = conf.leptos_options.site_addr;
    let leptos_options = conf.leptos_options;
    let routes = generate_route_list(App);
    let csp_value = "script-src 'self' https://cdn.tailwindcss.com 'wasm-unsafe-eval' 'unsafe-inline' chrome-extension://* moz-extension://*";

    let app = Router::new()
        .leptos_routes(&leptos_options, routes, {
            let leptos_options = leptos_options.clone();
            move || shell(leptos_options.clone())
        })
        .fallback(leptos_axum::file_and_error_handler(shell))
        .with_state(leptos_options)
        .layer(
            ServiceBuilder::new().layer(
                SetResponseHeaderLayer::overriding(
                    HeaderName::from_static("content-security-policy"),
                    HeaderValue::from_static(csp_value),
                ),
            ),
        );

    // run our app with hyper
    // `axum::Server` is a re-export of `hyper::Server`
    log!("listening on http://{}", &addr);
    let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
    axum::serve(listener, app.into_make_service())
        .await
        .unwrap();
}

#[cfg(not(feature = "ssr"))]
pub fn main() {
    // no client-side main function
    // unless we want this to work with e.g., Trunk for pure client-side testing
    // see lib.rs for hydration function instead
}
