<?php

namespace Openguru\OpenCartFramework\Cache;

use Openguru\OpenCartFramework\Container\Container;
use Openguru\OpenCartFramework\Container\ServiceProvider;
use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Predis\Client as PredisClient;

class CacheServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Регистрация DoctrineDbalAdapter для MySQL кеша
        $this->container->singleton(DoctrineDbalAdapter::class, function (Container $container) {
            $host = $container->getConfigValue('database.host');
            $username = $container->getConfigValue('database.username');
            $password = $container->getConfigValue('database.password');
            $port = (int) $container->getConfigValue('database.port');
            $dbName = $container->getConfigValue('database.database');

            $dsn = "mysql://$username:$password@$host:$port/$dbName?charset=utf8mb4";

            $namespace = $container->getConfigValue('cache.namespace');
            $defaultLifetime = $container->getConfigValue('cache.default_lifetime');
            $options = $container->getConfigValue('cache.options');

            return new DoctrineDbalAdapter($dsn, $namespace, $defaultLifetime, $options);
        });

        // Регистрация RedisAdapter для Redis кеша
        $this->container->singleton(RedisAdapter::class, function (Container $container) {
            $host = env('TELECART_REDIS_HOST', '127.0.0.1');
            $port = (int) env('TELECART_REDIS_PORT', 6379);
            $password = env('TELECART_REDIS_PASSWORD', null);
            $database = (int) env('TELECART_REDIS_DATABASE', 0);

            $redisConfig = [
                'host' => $host,
                'port' => $port,
                'database' => $database,
            ];

            if ($password !== null) {
                $redisConfig['password'] = $password;
            }

            $redisClient = new PredisClient($redisConfig);

            $namespace = $container->getConfigValue('cache.namespace');
            $defaultLifetime = $container->getConfigValue('cache.default_lifetime');

            return new RedisAdapter($redisClient, $namespace, $defaultLifetime);
        });

        // Регистрация CacheInterface с выбором драйвера
        $this->container->singleton(CacheInterface::class, function (Container $container) {
            $driver = env('TELECART_CACHE_DRIVER', 'mysql');

            if ($driver === 'redis') {
                return new SymfonyRedisCache($container->get(RedisAdapter::class));
            }

            // По умолчанию используем MySQL
            return new SymfonyMySqlCache($container->get(DoctrineDbalAdapter::class));
        });
    }
}
