<?php

declare(strict_types=1);

namespace App\Framework\StateManagement;

use App\Framework\Attributes\Initializer;
use App\Framework\Cache\Cache;
use App\Framework\Database\EntityManager;
use App\Framework\DI\Container;
use App\Framework\Logging\Logger;
use App\Framework\StateManagement\Database\DatabaseStateHistoryManager;
use App\Framework\StateManagement\Database\DatabaseStateManager;

/**
 * State Management System Initializer
 *
 * Registers state management services in DI container:
 * - DatabaseStateManager for persistent state storage
 * - DatabaseStateHistoryManager for audit trails
 * - LiveComponentStateManager wrapper (application layer)
 */
final readonly class StateManagementInitializer
{
    public function __construct(
        private EntityManager $entityManager,
        private Cache $cache,
        private ?Logger $logger = null,
    ) {}

    #[Initializer]
    public function initialize(Container $container): void
    {
        // Register StateHistoryManager
        $historyManager = new DatabaseStateHistoryManager(
            entityManager: $this->entityManager,
            logger: $this->logger
        );
        $container->singleton(StateHistoryManager::class, $historyManager);

        // Register StateManager with database backend
        // Note: The stateClass will be set by LiveComponentStateManager
        // This is a generic StateManager for framework-wide use
        $stateManager = new DatabaseStateManager(
            entityManager: $this->entityManager,
            cache: $this->cache,
            stateClass: '', // Will be overridden per component
            logger: $this->logger
        );
        $container->singleton(StateManager::class, $stateManager);
    }

    /**
     * Create StateManager for specific state class
     *
     * Factory method for creating state managers with specific state class configuration.
     * Useful for components that need typed state managers.
     *
     * @param string $stateClass Fully qualified state class name
     * @return StateManager State manager configured for specific state class
     */
    public function createForStateClass(string $stateClass): StateManager
    {
        return new DatabaseStateManager(
            entityManager: $this->entityManager,
            cache: $this->cache,
            stateClass: $stateClass,
            logger: $this->logger
        );
    }
}
