<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\Validation;

/**
 * Cache for component state schemas
 *
 * Stores derived schemas per component class to avoid repeated derivation.
 * Schema is derived once from first getData() call and reused for all
 * subsequent validations of that component class.
 *
 * Performance:
 * - Eliminates repeated get_debug_type() calls
 * - O(1) lookup by component class name
 * - Memory-efficient - one schema per component class
 */
final class SchemaCache
{
    /**
     * @var array<string, DerivedSchema> Component class => schema mapping
     */
    private array $cache = [];

    /**
     * Get cached schema for component class
     *
     * @param string $componentClass Fully qualified component class name
     * @return DerivedSchema|null Cached schema or null if not cached
     */
    public function get(string $componentClass): ?DerivedSchema
    {
        return $this->cache[$componentClass] ?? null;
    }

    /**
     * Store schema for component class
     *
     * @param string $componentClass Fully qualified component class name
     * @param DerivedSchema $schema Derived schema to cache
     */
    public function set(string $componentClass, DerivedSchema $schema): void
    {
        $this->cache[$componentClass] = $schema;
    }

    /**
     * Check if schema is cached for component class
     *
     * @param string $componentClass Fully qualified component class name
     */
    public function has(string $componentClass): bool
    {
        return isset($this->cache[$componentClass]);
    }

    /**
     * Clear cache for specific component class
     *
     * @param string $componentClass Fully qualified component class name
     */
    public function clear(string $componentClass): void
    {
        unset($this->cache[$componentClass]);
    }

    /**
     * Clear all cached schemas
     */
    public function clearAll(): void
    {
        $this->cache = [];
    }

    /**
     * Get cache statistics
     *
     * @return array{cached_count: int, cached_classes: array<string>}
     */
    public function getStats(): array
    {
        return [
            'cached_count' => count($this->cache),
            'cached_classes' => array_keys($this->cache),
        ];
    }
}
