<?php

declare(strict_types=1);

namespace App\Framework\Http;

/**
 *
 * class AuthMiddleware
 * {
 *      public function __invoke($context, $next, $state)
 *      {
 *          $auth = $state->namespace('auth');
 *
 *          $auth->set('user', $user);              Intern: 'auth.user'
 *          $auth->set('permissions', $perms);      Intern: 'auth.permissions'
 *
 *      return $next($context);
 *      }
 * }
 */

final readonly class NamespacedState
{
    public function __construct(
        private RequestStateManager $stateManager,
        private string              $namespace
    ) {
    }

    public function set(StateKey|string $key, mixed $value): void
    {
        $keyString = $key instanceof StateKey ? $key->value : $key;
        $this->stateManager->set("{$this->namespace}.{$keyString}", $value);
    }

    public function get(StateKey|string $key, mixed $default = null): mixed
    {
        $keyString = $key instanceof StateKey ? $key->value : $key;

        return $this->stateManager->get("{$this->namespace}.{$keyString}", $default);
    }
}
