<?php

declare(strict_types=1);

namespace App\Framework\Cache\Compression;

use App\Framework\Cache\CompressionAlgorithm;

final class GzipCompression implements CompressionAlgorithm
{
    private const string PREFIX = 'gz:';

    private int $level;

    private int $threshold;

    public function __construct(int $compressionLevel = -1, int $minLengthToCompress = 1024)
    {
        $this->level = $compressionLevel;
        $this->threshold = $minLengthToCompress;
    }

    public function compress(string $value, bool $forceCompression = false): string
    {
        if (! $forceCompression && strlen($value) < $this->threshold) {
            return $value;
        }
        $compressed = gzcompress($value, $this->level);
        if ($compressed === false) {
            // Fallback auf Originalwert bei Fehler
            return $value;
        }

        return self::PREFIX . $compressed;
    }

    public function decompress(string $value): string
    {
        if (! $this->isCompressed($value)) {
            return $value;
        }
        $raw = substr($value, strlen(self::PREFIX));
        $decompressed = @gzuncompress($raw);

        return $decompressed !== false ? $decompressed : $value;
    }

    public function isCompressed(string $value): bool
    {
        return strncmp($value, self::PREFIX, strlen(self::PREFIX)) === 0;
    }
}
