<?php

namespace Velis\Session;

use Phalcon\Session\Adapter\Stream;
use Phalcon\Session\Manager;
use Phalcon\Storage\AdapterFactory;
use Phalcon\Storage\SerializerFactory;
use Redis;
use RedisException;
use Velis\Session\Storage\Phalcon4RedisStorageAdapter;
use Velis\Session\Adapter\Phalcon4RedisAdapter;
use Velis\Session\Serializer\DefaultSerializer;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class SessionFactory implements SessionFactoryInterface
{
    /**
     * {@inheritDoc}
     */
    public function createFileSession(array $config): SessionInterface
    {
        if (!isset($config['savePath'])) {
            $config['savePath'] = '/tmp';
        }

        $manager = new Manager();
        $manager->setAdapter(new Stream($config));

        return new Session($manager);
    }

    /**
     * {@inheritDoc}
     * @throws RedisException
     */
    public function createRedisSession(array $config): SessionInterface
    {
        $serializerFactory = new SerializerFactory();
        $adapterFactory = new AdapterFactory(
            $serializerFactory,
            ['redis' => Phalcon4RedisStorageAdapter::class]
        );

        $manager = new Manager();
        $manager->setAdapter(new Phalcon4RedisAdapter($adapterFactory, $config));

        $redisClient = new Redis();
        $redisClient->connect($config['host'], $config['port'] ?? 6379);
        $serializer = new DefaultSerializer();

        return new RedisSession($manager, $redisClient, $config['lifetime'] ?? null, $serializer);
    }
}
