<?php

namespace Openguru\OpenCartFramework\Cache;

use Openguru\OpenCartFramework\Container\Container;
use Openguru\OpenCartFramework\Container\ServiceProvider;
use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;

class CacheServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $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);
        });

        $this->container->singleton(CacheInterface::class, function (Container $container) {
            return new SymfonyMySqlCache($container->get(DoctrineDbalAdapter::class));
        });
    }
}
