use aide::axum::ApiRouter;
use axum::{
    body::{boxed, Full},
    response::{Html, IntoResponse, Response},
    routing::get,
};
use hyper::{header, StatusCode, Uri};
use rust_embed::RustEmbed;

pub fn routes() -> ApiRouter {
    ApiRouter::new()
        .route("/*file", get(static_handler))
        .route("/", get(index))
}

async fn index() -> Html<&'static str> {
    Html(include_str!("../web/dist/index.html"))
}

async fn static_handler(uri: Uri) -> impl IntoResponse {
    let path = uri.path().trim_start_matches('/');

    if path.starts_with("/api/") {
        return StatusCode::NOT_FOUND.into_response();
    }

    match Assets::get(path) {
        Some(v) => {
            tracing::debug!("found file: {}", path);
            let body = boxed(Full::from(v.data));
            let mime = mime_guess::from_path(path).first_or_octet_stream();

            Response::builder()
                .header(header::CONTENT_TYPE, mime.as_ref())
                .body(body)
                .unwrap()
        }
        // return index.html, vue router will handle the rest
        None => index().await.into_response(),
    }
}

#[derive(RustEmbed)]
#[folder = "web/dist/"]
struct Assets;
