#[cfg(debug_assertions)]
pub use serve_static_debug::{root_index, serve_static_content};
#[cfg(not(debug_assertions))]
pub use serve_static_release::{root_index, serve_static_content};

#[cfg(debug_assertions)]
mod serve_static_debug {
    use actix_web::{HttpResponse, Responder};

    pub async fn root_index() -> impl Responder {
        HttpResponse::Ok().body("Hello world! Debug=on for Money manager!")
    }

    pub async fn serve_static_content() -> impl Responder {
        HttpResponse::NotFound().body("Hello world! Static assets are not served in debug mode")
    }
}

#[cfg(not(debug_assertions))]
mod serve_static_release {
    use actix_web::{HttpResponse, Responder, web};
    use rust_embed::RustEmbed;

    #[derive(RustEmbed)]
    #[folder = "static/"]
    struct Asset;

    fn handle_embedded_file(path: &str, can_fallback: bool) -> HttpResponse {
        match (Asset::get(path), can_fallback) {
            (Some(content), _) => HttpResponse::Ok()
                .content_type(mime_guess::from_path(path).first_or_octet_stream().as_ref())
                .body(content.data.into_owned()),
            (None, false) => HttpResponse::NotFound().body("404 Not Found"),
            (None, true) => handle_embedded_file("index.html", false),
        }
    }

    pub async fn root_index() -> impl Responder {
        handle_embedded_file("index.html", false)
    }

    pub async fn serve_static_content(path: web::Path<String>) -> impl Responder {
        handle_embedded_file(path.as_ref(), !path.as_ref().starts_with("static/"))
    }
}
