//! Helpers for extracting the `X-User-Id` header.
use actix_web::HttpRequest;

/// Returns the user identifier supplied by the caller.
pub fn get_x_user_id(req: &HttpRequest) -> Option<String> {
    req.headers()
        .get("X-User-Id")
        .and_then(|h| h.to_str().ok())
        .map(|s| s.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::test::TestRequest;

    #[actix_web::test]
    async fn returns_none_when_missing() {
        let req: HttpRequest = TestRequest::default().to_http_request();
        assert!(get_x_user_id(&req).is_none());
    }

    #[actix_web::test]
    async fn returns_value_when_present() {
        let req: HttpRequest = TestRequest::default()
            .insert_header(("X-User-Id", "user-123"))
            .to_http_request();
        assert_eq!(get_x_user_id(&req).unwrap(), "user-123");
    }
}
