<?php
declare(strict_types=1);

namespace App\Framework\Http\Session;

use Predis\Client;

/**
 * Implementation of the SessionStorage interface using Redis as the storage backend.
 * This class provides methods to read, write, remove, and migrate session data stored in Redis.
 */
final class RedisSessionStorage implements SessionStorage
{
    private const string PREFIX = 'session:';

    public function __construct(
        private readonly Client $redis = new Client([
            'scheme' => 'tcp',
            'host' => 'redis',
            'port' => 6379,
            'parameters' => []
        ]),
        private readonly int $ttl = 3600 // 1 Stunde standardmäßig
    ) {
        #$this->redis->connect();
    }

    public function read(SessionId $id): array
    {
        $data = $this->redis->get($this->getKey($id));

        if ($data === null) {
            return [];
        }

        return json_decode($data, true) ?? [];
    }

    public function write(SessionId $id, array $data): void
    {
        $this->redis->setex(
            $this->getKey($id),
            $this->ttl,
            json_encode($data)
        );
    }

    public function remove(SessionId $id): void
    {
        $this->redis->del($this->getKey($id));
    }

    public function migrate(SessionId $fromId, SessionId $toId): void
    {
        $data = $this->read($fromId);
        $this->write($toId, $data);
        $this->remove($fromId);
    }

    private function getKey(SessionId $id): string
    {
        return self::PREFIX . $id->toString();
    }
}
