Skip to content
use std::sync::LazyLock;

use actix_web::{HttpRequest, HttpResponse, Responder, get};

const TCSS: &str = include_str!("../assets/t.css");
const THEME_CSS: &str = include_str!("../assets/theme.css");
const FAVICON: &str = include_str!("../assets/favicon.svg");
const HTMX: &str = include_str!("../assets/h.js");
const HTMX_RESPONSE_TARGETS: &str = include_str!("../assets/hx-response-targets.js");
const GSAP: &str = include_str!("../assets/gsap.min.js");
const GSAP_SCROLL_TRIGGER: &str = include_str!("../assets/ScrollTrigger.min.js");
const MAIN_JS: &str = include_str!("../assets/main.js");

static CACHE_CONTROL_VALUE: LazyLock<String> = LazyLock::new(|| {
    std::env::var("ASSET_CACHE_CONTROL").unwrap_or_else(|_| "public, max-age=86400".to_string())
});

pub(crate) fn cache_control_value() -> &'static str {
    CACHE_CONTROL_VALUE.as_str()
}

#[get("/assets/{filename:.*}")]
pub async fn assets(req: HttpRequest) -> impl Responder {
    let path = req.match_info().query("filename");

    match path {
        "t.css" => HttpResponse::Ok()
            .content_type("text/css; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(TCSS),
        "theme.css" => HttpResponse::Ok()
            .content_type("text/css; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(THEME_CSS),
        "favicon.svg" => HttpResponse::Ok()
            .content_type("image/svg+xml")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(FAVICON),
        "h.js" => HttpResponse::Ok()
            .content_type("application/javascript; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(HTMX),
        "hx-response-targets.js" => HttpResponse::Ok()
            .content_type("application/javascript; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(HTMX_RESPONSE_TARGETS),
        "gsap.min.js" => HttpResponse::Ok()
            .content_type("application/javascript; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(GSAP),
        "ScrollTrigger.min.js" => HttpResponse::Ok()
            .content_type("application/javascript; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(GSAP_SCROLL_TRIGGER),
        "main.js" => HttpResponse::Ok()
            .content_type("application/javascript; charset=utf-8")
            .insert_header(("Cache-Control", CACHE_CONTROL_VALUE.as_str()))
            .body(MAIN_JS),
        _ => HttpResponse::NotFound().body("Not found"),
    }
}