<?php

declare(strict_types=1);

namespace Apexl\Io\Cache\Factories;

use Apexl\Io\Cache\Dtos\RedisCacheDriverConfig;
use Apexl\Io\Cache\Dtos\RedisCacheDriverServerConfig;
use Apexl\Io\Cache\Interfaces\CacheDriverFactoryInterface;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use Stash\Driver\Redis;
use Stash\Interfaces\DriverInterface;

/**
 * @Todo lazy load drivers
 */
final readonly class RedisCacheDriverFactory implements CacheDriverFactoryInterface
{
    public function __construct(private Container $container) {}

    /**
     * @throws DependencyException
     * @throws NotFoundException
     */
    public function make(array $options = []): DriverInterface
    {
        $config = RedisCacheDriverConfig::fromArray($options);

        return $this->container->make(Redis::class, [
            'options' => [
                'servers' => $config->servers->map(
                    fn(RedisCacheDriverServerConfig $serverConfig) => $serverConfig->toArray()
                )->toArray(),
            ]
        ]);
    }

    public function loadable(array $options): bool
    {
        if (!Redis::isAvailable()) {
            return false;
        }
        
        $config = RedisCacheDriverConfig::fromArray($options);

        return $config->servers->count() > 0;
    }
}