<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\Caching;

use App\Framework\Cache\Cache;
use App\Framework\DI\Attributes\Initializer;
use App\Framework\DI\Container;
use App\Framework\Http\Request;
use App\Framework\LiveComponents\ComponentCacheManager;

/**
 * Component Cache Manager Initializer
 *
 * Registers ComponentCacheManager with CacheContext based on current request.
 */
final readonly class ComponentCacheManagerInitializer
{
    public function __construct(
        private Cache $cache,
        private CacheKeyBuilder $cacheKeyBuilder
    ) {
    }

    #[Initializer]
    public function __invoke(Container $container): ComponentCacheManager
    {
        // Try to get CacheContext from request if available
        $cacheContext = $this->resolveCacheContext($container);

        return new ComponentCacheManager(
            cache: $this->cache,
            cacheKeyBuilder: $this->cacheKeyBuilder,
            cacheContext: $cacheContext
        );
    }

    /**
     * Resolve CacheContext from current request
     */
    private function resolveCacheContext(Container $container): ?CacheContext
    {
        try {
            $request = $container->get(Request::class);

            // Extract user context from request
            // This is a basic implementation - customize based on your auth system
            $userId = $request->session?->get('user_id');
            $locale = $request->headers->getFirst('Accept-Language') ?? 'en';
            $roles = $request->session?->get('user_roles', []);
            $featureFlags = $request->session?->get('feature_flags', []);

            if ($userId !== null) {
                return CacheContext::forUser(
                    userId: (string) $userId,
                    roles: is_array($roles) ? $roles : [],
                    locale: $locale
                )->withFeatureFlags($featureFlags);
            }

            return CacheContext::guest($locale);
        } catch (\Throwable) {
            // No request context available (e.g., CLI)
            return null;
        }
    }
}
