use actix_web::{web, HttpResponse, Responder};
use tracing::{debug, error};

use crate::handlers::STATIC_DIR;

pub async fn serve_static_files(path: web::Path<String>) -> impl Responder {
    let file_path = path.into_inner();

    debug!("请求静态文件: {}", file_path);

    match STATIC_DIR.get_file(&file_path) {
        Some(file) => {
            let content_type = match file_path.split('.').next_back() {
                Some("ico") => "image/x-icon",
                Some("png") => "image/png",
                Some("jpg") | Some("jpeg") => "image/jpeg",
                Some("gif") => "image/gif",
                Some("svg") => "image/svg+xml",
                Some("webp") => "image/webp",
                Some("css") => "text/css",
                Some("js") => "application/javascript",
                Some("html") => "text/html",
                Some("ttf") => "font/ttf",
                Some("woff") => "font/woff",
                Some("woff2") => "font/woff2",
                _ => "application/octet-stream",
            };

            debug!("成功找到文件: {}, Content-Type: {}", file_path, content_type);
            HttpResponse::Ok()
                .content_type(content_type)
                .body(file.contents())
        }
        None => {
            error!("文件未找到: {}", file_path);
            HttpResponse::NotFound().body("静态文件不存在")
        }
    }
}
