use axum::{
    body::Body,
    extract::Request,
    http::StatusCode,
    middleware::Next,
    response::{IntoResponse, Response},
};

use crate::rest::response::ApiResponse;

/// Converts non-success status responses into the uniform response envelope.
pub async fn uniform_error_middleware(request: Request<Body>, next: Next) -> Response {
    let response = next.run(request).await;
    let status = response.status();

    if status.is_client_error() || status.is_server_error() {
        let code = status.as_u16().to_string();
        let message = status
            .canonical_reason()
            .unwrap_or("request failed")
            .to_string();

        return ApiResponse::<()>::fail(code, message).into_response();
    }

    if status == StatusCode::NO_CONTENT {
        return ApiResponse::<()>::success_no_data().into_response();
    }

    response
}
