using System.Buffers;
using System.Text;
using AyCode.Core.Compression;

namespace AyCode.Core.Tests.Compression;

[TestClass]
public class GzipHelperTests
{
    [TestMethod]
    public void CompressAndDecompress_StringRoundTrip_Succeeds()
    {
        var original = "SignalR payload for gzip";

        var compressed = GzipHelper.Compress(original);
        var decompressed = GzipHelper.DecompressToString(compressed);

        Assert.IsNotNull(compressed);
        Assert.AreNotEqual(0, compressed.Length);
        Assert.AreEqual(original, decompressed);
    }

    [TestMethod]
    public void DecompressToRentedBuffer_ReturnsOriginalBytes()
    {
        var payload = "{\"message\":\"gzip\"}";
        var compressed = GzipHelper.Compress(payload);

        var (buffer, length) = GzipHelper.DecompressToRentedBuffer(compressed);
        try
        {
            Assert.IsTrue(length > 0);
            var text = Encoding.UTF8.GetString(buffer, 0, length);
            Assert.AreEqual(payload, text);
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer);
        }
    }

    [TestMethod]
    public void IsGzipCompressed_ReturnsExpectedValues()
    {
        var compressed = GzipHelper.Compress("ping");
        var nonCompressed = Encoding.UTF8.GetBytes("plain text");

        Assert.IsTrue(GzipHelper.IsGzipCompressed(compressed));
        Assert.IsFalse(GzipHelper.IsGzipCompressed(nonCompressed));
        Assert.IsFalse(GzipHelper.IsGzipCompressed(Array.Empty<byte>()));
    }
}
