use crate::{
    http::{
        error::AppError,
        response::{reply, HandlerResponse},
    },
    node::{
        stack::{list, NodeInfo},
        system::{system_info, SystemInfo},
    },
    AppState,
};
use askama::Template;
use axum::{extract::State, response::IntoResponse, routing::get, Json, Router};
use serde_json::json;

use self::assets::static_path;

mod assets;
mod container;
mod stack;

#[derive(Template)]
#[template(path = "home.html")]
struct HomeTemplate {
    info: NodeInfo,
    system: SystemInfo,
}

async fn home(State(state): State<AppState>) -> HandlerResponse {
    let info = list(&state.stack_dir, &state.docker)
        .await
        .map_err(AppError::from)?;
    let system = system_info();
    reply(
        json!({ "info": info, "system": system }),
        HomeTemplate { info, system },
    )
}

async fn get_sys_info() -> impl IntoResponse {
    Json(system_info())
}

pub(crate) fn router() -> Router<AppState> {
    Router::new()
        .route("/static/*path", get(static_path))
        .route("/", get(home))
        .route("/sysinfo", get(get_sys_info))
        .nest("/stack", stack::router())
        .nest("/container", container::router())
}