<?php

declare(strict_types=1);

namespace App\Application\Debug;

use App\Framework\Cache\Cache;
use App\Framework\Cache\CacheKey;
use App\Framework\Core\ValueObjects\Duration;

/**
 * Debug History Manager
 *
 * Manages command history for the debug console.
 * Uses cache for persistence across requests.
 */
final readonly class DebugHistoryManager
{
    private const CACHE_KEY = 'debug_console_history';
    private const MAX_HISTORY_SIZE = 100;

    public function __construct(
        private Cache $cache
    ) {
    }

    public function addEntry(string $code, EvaluationResult $result): void
    {
        $history = $this->getHistory();

        $entry = [
            'code' => $code,
            'output' => $result->output,
            'type' => $result->type,
            'executionTime' => $result->executionTime,
            'timestamp' => time(),
        ];

        // Add to beginning of array
        array_unshift($history, $entry);

        // Limit size
        if (count($history) > self::MAX_HISTORY_SIZE) {
            $history = array_slice($history, 0, self::MAX_HISTORY_SIZE);
        }

        // Save to cache (24 hour TTL)
        $this->cache->set(
            CacheKey::fromString(self::CACHE_KEY),
            $history,
            Duration::fromHours(24)
        );
    }

    public function getHistory(int $limit = 50): array
    {
        $history = $this->cache->get(CacheKey::fromString(self::CACHE_KEY)) ?? [];

        if ($limit > 0 && count($history) > $limit) {
            $history = array_slice($history, 0, $limit);
        }

        return $history;
    }

    public function clearHistory(): void
    {
        $this->cache->delete(CacheKey::fromString(self::CACHE_KEY));
    }
}
