<?php

declare(strict_types=1);

namespace App\Framework\Discovery\Events;

use App\Framework\Cache\CacheKey;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Discovery\ValueObjects\CacheLevel;

/**
 * Cache miss event
 *
 * Emitted when a cache lookup fails to find the requested data.
 */
final readonly class CacheMissEvent
{
    public function __construct(
        public CacheKey $cacheKey,
        public string $reason,
        public CacheLevel $cacheLevel,
        public Timestamp $timestamp
    ) {
    }

    /**
     * Get miss reason category
     */
    public function getReasonCategory(): string
    {
        return match ($this->reason) {
            'not_found' => 'miss',
            'expired' => 'expiration',
            'evicted' => 'eviction',
            'corrupted' => 'corruption',
            default => 'unknown'
        };
    }

    /**
     * Check if this miss could have been prevented
     */
    public function isPreventable(): bool
    {
        return in_array($this->reason, ['expired', 'evicted']);
    }

    /**
     * Convert to array for serialization
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'cache_key' => $this->cacheKey->toString(),
            'reason' => $this->reason,
            'reason_category' => $this->getReasonCategory(),
            'cache_level' => $this->cacheLevel->value,
            'is_preventable' => $this->isPreventable(),
            'timestamp' => $this->timestamp->toFloat(),
        ];
    }
}
