// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

use async_compression::Level;
use async_compression::tokio::write::{BrotliEncoder, GzipEncoder, ZlibEncoder, ZstdEncoder};
use bytes::Bytes;
use tokio::io::AsyncWriteExt;

pub async fn get_compressed(payload: &[u8], compression: &str) -> Bytes {
    match compression {
        "gzip" => {
            let mut encoder = GzipEncoder::new(Vec::new());
            if let Err(err) = encoder.write_all(payload.as_ref()).await {
                tracing::error!(%err);
            }
            if let Err(err) = encoder.shutdown().await {
                tracing::error!(%err);
            }
            Bytes::copy_from_slice(encoder.into_inner().as_slice())
        }
        "zstd" => {
            let mut encoder = ZstdEncoder::with_quality(Vec::new(), Level::Precise(17));
            if let Err(err) = encoder.write_all(payload).await {
                tracing::error!(%err);
            }
            if let Err(err) = encoder.shutdown().await {
                tracing::error!(%err);
            }
            Bytes::copy_from_slice(encoder.into_inner().as_slice())
        }
        "br" => {
            let mut encoder = BrotliEncoder::new(Vec::new());
            if let Err(err) = encoder.write_all(payload).await {
                tracing::error!(%err);
            }
            if let Err(err) = encoder.shutdown().await {
                tracing::error!(%err);
            }
            Bytes::copy_from_slice(encoder.into_inner().as_slice())
        }
        "deflate" => {
            let mut encoder = ZlibEncoder::new(Vec::new());
            if let Err(err) = encoder.write_all(payload).await {
                tracing::error!(%err);
            }
            if let Err(err) = encoder.shutdown().await {
                tracing::error!(%err);
            }
            Bytes::copy_from_slice(encoder.into_inner().as_slice())
        }
        _ => Bytes::copy_from_slice(payload),
    }
}
