<?php

namespace App\Framework\Http;

use WeakMap;

final class RequestStateManager
{
    public function __construct(
        private WeakMap          $requestStates,
        private readonly Request $request,
    ) {}

    public function namespace(string $namespace): NamespacedState
    {
        return new NamespacedState($this, $namespace);
    }

    public function set(string $key, mixed $value): void
    {
        if(!isset($this->requestStates[$this->request])) {
            $this->requestStates[$this->request] = [];
        }
        $this->requestStates[$this->request][$key] = $value;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        return $this->requestStates[$this->request][$key] ?? $default;
    }

    public function has(string $key): bool
    {
        return isset($this->requestStates[$this->request][$key]);
    }

    public function remove(string $key): void
    {
        unset($this->requestStates[$this->request][$key]);
    }
}
