<?php

declare(strict_types=1);

namespace App\Framework\Database\Cache;

use App\Framework\Core\Events\EventDispatcher;
use App\Framework\Database\Config\DatabaseConfig;
use App\Framework\Database\IdentityMap;
use App\Framework\Database\Metadata\MetadataRegistry;
use App\Framework\Database\TypeConverter;
use App\Framework\DI\Container;
use App\Framework\DI\Initializer;
use App\Framework\Redis\RedisConnectionInterface;

final readonly class SecondLevelCacheInitializer
{
    #[Initializer]
    public function __invoke(Container $container): EntityCacheManager
    {
        $databaseConfig = $container->get(DatabaseConfig::class);

        // Check if second-level cache is enabled
        $cacheEnabled = $databaseConfig->cacheConfig->enabled;

        if (! $cacheEnabled) {
            // Return disabled cache manager
            return new EntityCacheManager(
                new NullSecondLevelCache(),
                $container->get(IdentityMap::class),
                $container->get(MetadataRegistry::class),
                false
            );
        }

        // Get required dependencies
        $redisConnection = $container->get(RedisConnectionInterface::class);
        $eventDispatcher = $container->get(EventDispatcher::class);
        $metadataRegistry = $container->get(MetadataRegistry::class);
        $typeConverter = $container->get(TypeConverter::class);
        $identityMap = $container->get(IdentityMap::class);

        // Create the cache manager
        return SecondLevelCacheFactory::create(
            $redisConnection,
            $eventDispatcher,
            $metadataRegistry,
            $typeConverter,
            $identityMap,
            $cacheEnabled
        );
    }
}
