<?php

declare(strict_types=1);

namespace App\Framework\ErrorHandling;

use App\Framework\ErrorHandling\Handlers\ErrorHandlerInterface;

/**
 * Registry for named error handlers
 *
 * Allows handlers to be registered and retrieved by name
 *
 * Immutable: All modification methods return new instances
 */
final readonly class ErrorHandlerRegistry
{
    /**
     * @param array<string, ErrorHandlerInterface> $handlers
     */
    public function __construct(
        private array $handlers = []
    ) {}

    /**
     * Register a handler with a name (immutable)
     *
     * @return self New instance with handler registered
     */
    public function register(string $name, ErrorHandlerInterface $handler): self
    {
        $newHandlers = [...$this->handlers];
        $newHandlers[$name] = $handler;

        return new self($newHandlers);
    }

    /**
     * Get a handler by name
     */
    public function get(string $name): ?ErrorHandlerInterface
    {
        return $this->handlers[$name] ?? null;
    }

    /**
     * Check if a handler is registered
     */
    public function has(string $name): bool
    {
        return isset($this->handlers[$name]);
    }

    /**
     * Get all registered handlers
     *
     * @return array<string, ErrorHandlerInterface>
     */
    public function all(): array
    {
        return $this->handlers;
    }

    /**
     * Remove a handler by name (immutable)
     *
     * @return self New instance without the specified handler
     */
    public function unregister(string $name): self
    {
        $newHandlers = $this->handlers;
        unset($newHandlers[$name]);

        return new self($newHandlers);
    }

    /**
     * Clear all handlers (immutable)
     *
     * @return self New instance with no handlers
     */
    public function clear(): self
    {
        return new self([]);
    }
}
