// SPDX-License-Identifier: Apache-2.0
//! SSR server entry point — compiled only with the `ssr` feature.
//!
//! Starts an Axum server that:
//!   1. Renders Leptos routes server-side via `leptos_axum`.
//!   2. Injects the hydration Wasm bundle built by cargo-leptos.
//!   3. Serves compiled CSS, the Wasm bundle, and public assets.

#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
    use axum::Router;
    use hejpics_web::app::{App, shell};
    use leptos::config::{LeptosOptions, get_configuration};
    use leptos_axum::{LeptosRoutes, generate_route_list};

    // cargo-leptos injects LEPTOS_SITE_ROOT, LEPTOS_SITE_ADDR, etc. as
    // environment variables. get_configuration(None) reads them directly —
    // no leptos.toml file is needed at runtime.
    let conf =
        get_configuration(None).expect("failed to read Leptos configuration from environment");

    let leptos_options = conf.leptos_options;
    let addr = leptos_options.site_addr;
    let routes = generate_route_list(App);

    // The router state is `LeptosOptions`; specifying this type explicitly
    // satisfies the `LeptosOptions: FromRef<S>` bound required by
    // `LeptosRoutes` and `file_and_error_handler`.
    let app = Router::<LeptosOptions>::new()
        .leptos_routes(&leptos_options, routes, {
            let lo = leptos_options.clone();
            move || shell(lo.clone())
        })
        .fallback(leptos_axum::file_and_error_handler(shell))
        .with_state(leptos_options);

    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .unwrap_or_else(|e| panic!("cannot bind {addr}: {e}"));

    println!("hejpics SSR server → http://{addr}");

    axum::serve(listener, app.into_make_service())
        .await
        .expect("server error");
}

#[cfg(not(feature = "ssr"))]
fn main() {}
