<?php

declare(strict_types=1);

namespace App\Framework\Discovery\Events;

use App\Framework\Core\ValueObjects\Byte;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Discovery\ValueObjects\CompressionLevel;

/**
 * Cache compression event
 *
 * Emitted when cache data is compressed to reduce memory usage.
 */
final readonly class CacheCompressionEvent
{
    public function __construct(
        public Byte $originalSize,
        public Byte $compressedSize,
        public CompressionLevel $compressionLevel,
        public float $compressionRatio,
        public Timestamp $timestamp
    ) {
    }

    /**
     * Get memory savings from compression
     */
    public function getMemorySavings(): Byte
    {
        return $this->originalSize->subtract($this->compressedSize);
    }

    /**
     * Get compression effectiveness
     */
    public function getEffectiveness(): string
    {
        return match (true) {
            $this->compressionRatio <= 0.3 => 'excellent',  // 70%+ compression
            $this->compressionRatio <= 0.5 => 'good',       // 50-70% compression
            $this->compressionRatio <= 0.7 => 'moderate',   // 30-50% compression
            $this->compressionRatio <= 0.9 => 'low',        // 10-30% compression
            default => 'poor'                               // < 10% compression
        };
    }

    /**
     * Check if compression was beneficial
     */
    public function wasBeneficial(): bool
    {
        return $this->compressionRatio < 0.9; // At least 10% reduction
    }

    /**
     * Convert to array for serialization
     */
    public function toArray(): array
    {
        return [
            'original_size' => $this->originalSize->toHumanReadable(),
            'compressed_size' => $this->compressedSize->toHumanReadable(),
            'compression_level' => $this->compressionLevel->value,
            'compression_ratio' => round($this->compressionRatio * 100, 2) . '%',
            'memory_savings' => $this->getMemorySavings()->toHumanReadable(),
            'effectiveness' => $this->getEffectiveness(),
            'was_beneficial' => $this->wasBeneficial(),
            'timestamp' => $this->timestamp->toFloat(),
        ];
    }
}
