<?php

declare(strict_types=1);

namespace Tests\Support;

use App\Framework\LiveComponents\Services\UploadSessionStore;
use App\Framework\LiveComponents\ValueObjects\UploadSession;
use App\Framework\LiveComponents\ValueObjects\UploadSessionId;
use DateTimeImmutable;

/**
 * In-Memory Upload Session Store for Testing
 *
 * Thread-safe in-memory implementation of UploadSessionStore
 * for use in tests. Does not require database or cache.
 */
final class InMemoryUploadSessionStore implements UploadSessionStore
{
    /** @var array<string, UploadSession> */
    private array $sessions = [];

    public function save(UploadSession $session): void
    {
        $this->sessions[$session->sessionId->value] = $session;
    }

    public function get(UploadSessionId $sessionId): ?UploadSession
    {
        return $this->sessions[$sessionId->value] ?? null;
    }

    public function delete(UploadSessionId $sessionId): void
    {
        unset($this->sessions[$sessionId->value]);
    }

    public function exists(UploadSessionId $sessionId): bool
    {
        return isset($this->sessions[$sessionId->value]);
    }

    public function cleanupExpired(): int
    {
        $now = new DateTimeImmutable();
        $cleaned = 0;

        foreach ($this->sessions as $key => $session) {
            if ($session->isExpired()) {
                unset($this->sessions[$key]);
                $cleaned++;
            }
        }

        return $cleaned;
    }

    /**
     * Get all stored sessions (for testing)
     *
     * @return array<UploadSession>
     */
    public function getAll(): array
    {
        return array_values($this->sessions);
    }

    /**
     * Get count of stored sessions (for testing)
     */
    public function count(): int
    {
        return count($this->sessions);
    }

    /**
     * Clear all sessions (for testing)
     */
    public function clear(): void
    {
        $this->sessions = [];
    }
}
