//! Retrieves the `X-Athena-Deadpool-Enable` header (experimental).
//!
//! When set to a truthy value, Athena may attempt to route Postgres gateway
//! operations through the deadpool-postgres backend (if compiled in).
use actix_web::HttpRequest;
use tracing::warn;

pub const ATHENA_DEADPOOL_ENABLE_HEADER: &str = "X-Athena-Deadpool-Enable";

fn parse_boolish(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Some(true),
        "false" | "0" | "no" | "off" => Some(false),
        _ => None,
    }
}

/// Returns whether deadpool routing was requested by the caller.
///
/// Missing or invalid values are treated as `false`.
pub fn x_athena_deadpool_enable(req: &HttpRequest, request_id: Option<&str>) -> bool {
    let Some(raw) = req
        .headers()
        .get(ATHENA_DEADPOOL_ENABLE_HEADER)
        .or_else(|| req.headers().get("x-athena-deadpool-enable"))
        .and_then(|value| value.to_str().ok())
    else {
        return false;
    };

    match parse_boolish(raw) {
        Some(value) => value,
        None => {
            warn!(
                request_id = request_id.unwrap_or(""),
                header = ATHENA_DEADPOOL_ENABLE_HEADER,
                value = raw,
                "Invalid X-Athena-Deadpool-Enable header value; ignoring"
            );
            false
        }
    }
}
