<?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\CacheLevel;

/**
 * Cache eviction event
 *
 * Emitted when cache items are evicted due to memory pressure
 * or other cache management policies.
 */
final readonly class CacheEvictionEvent
{
    public function __construct(
        public string $reason,
        public int $itemsEvicted,
        public Byte $memoryFreed,
        public CacheLevel $cacheLevel,
        public Timestamp $timestamp
    ) {
    }

    /**
     * Check if this was an emergency eviction
     */
    public function isEmergencyEviction(): bool
    {
        return in_array($this->reason, ['critical_cleanup', 'emergency_memory', 'out_of_memory']);
    }

    /**
     * Get eviction effectiveness
     */
    public function getEffectiveness(): string
    {
        return match (true) {
            $this->memoryFreed->greaterThan(Byte::fromMegabytes(50)) => 'high',
            $this->memoryFreed->greaterThan(Byte::fromMegabytes(10)) => 'medium',
            $this->memoryFreed->greaterThan(Byte::zero()) => 'low',
            default => 'none'
        };
    }

    /**
     * Convert to array for serialization
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'reason' => $this->reason,
            'items_evicted' => $this->itemsEvicted,
            'memory_freed' => $this->memoryFreed->toHumanReadable(),
            'cache_level' => $this->cacheLevel->value,
            'is_emergency' => $this->isEmergencyEviction(),
            'effectiveness' => $this->getEffectiveness(),
            'timestamp' => $this->timestamp->toFloat(),
        ];
    }
}
