use super::message::{CompressionRatio, WireCodecError};
use super::rpc::number::ByteCount;

pub fn validate_body_size(size: usize, limit: ByteCount) -> Result<(), WireCodecError> {
    if (size as u64) <= limit.get() {
        return Ok(());
    }
    Err(WireCodecError::new(
        format!("wire body has {size} bytes, limit is {}", limit.get()),
        "lower the message size or send large data through object storage",
    ))
}

pub fn validate_raw_size(size: usize, limit: ByteCount) -> Result<(), WireCodecError> {
    if (size as u64) <= limit.get() {
        return Ok(());
    }
    Err(WireCodecError::new(
        format!(
            "wire message expands to {size} bytes, limit is {}",
            limit.get()
        ),
        "lower the message size or raise WireLimits::max_raw",
    ))
}

pub fn validate_ratio(
    raw: usize,
    body: usize,
    limit: CompressionRatio,
) -> Result<(), WireCodecError> {
    if raw == 0 || (body != 0 && raw <= body.saturating_mul(usize::from(limit.get()))) {
        return Ok(());
    }
    Err(WireCodecError::new(
        "compressed wire message exceeds the allowed expansion ratio",
        "reject the packet or raise WireLimits::max_ratio for this service",
    ))
}
