use super::route_prelude::*;
use mime_guess::Mime;
use std::path::Path;
use std::str::FromStr;

/// Route to serve files from http/https URLs over Gemini
pub async fn route_www_get(ctx: RouteContext) -> Response {
    let Some(query) = decode_query(&ctx) else {
        return Response::input("URL");
    };

    let Ok(url) = Url::parse(&query) else {
        return Response::temporary_failure("Invalid URL");
    };

    match ehttp::fetch_async(ehttp::Request::get(&url)).await {
        Ok(resp) => {
            let mime_from_content =
                Mime::from_str(tree_magic_mini::from_u8(&resp.bytes))
                    .unwrap_or(mime::APPLICATION_OCTET_STREAM);

            let mime_type = match Path::new(url.path()).file_name() {
                Some(filename) => mime_guess::from_path(filename)
                    .first()
                    .unwrap_or(mime_from_content),
                None => mime_from_content,
            };

            Response::binary_success(&resp.bytes, mime_type.to_string())
        }
        Err(err) => {
            Response::temporary_failure(format!("Failed to fetch file: {err}"))
        }
    }
}
