use axum::extract::Request;
use axum::http::{HeaderName, HeaderValue};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use serde_json::json;
use super::error::UhpFailure;
pub const VERSION: &str = "2026-08-11";
pub const SUPPORTED: &[&str] = &[VERSION];
pub const HEADER: &str = "uhp-version";
pub async fn negotiate(request: Request, next: Next) -> Response {
if let Some(asked) = request.headers().get(HEADER) {
let asked = asked.to_str().unwrap_or_default();
if !asked.is_empty() && !SUPPORTED.contains(&asked) {
return UhpFailure::new(
super::error::ErrorType::InvalidRequestError,
"unsupported_protocol_version",
format!("this server does not speak protocol version '{asked}'"),
)
.with_detail(json!({ "supported": SUPPORTED }))
.into_response();
}
}
let mut response = next.run(request).await;
response.headers_mut().insert(
HeaderName::from_static(HEADER),
HeaderValue::from_static(VERSION),
);
response
}