<?php

declare(strict_types=1);

namespace App\Handler;

use Pkirillw\MaxBotApi\Scheme\Update\UpdateInterface;
use Psr\Log\LoggerInterface;

final class UpdateRouter
{
    /** @var list<UpdateHandlerInterface> */
    private array $handlers = [];

    public function __construct(
        private LoggerInterface $logger,
    ) {}

    public function add(UpdateHandlerInterface $handler): void
    {
        $this->handlers[] = $handler;
    }

    public function dispatch(object $update): void
    {
        if (!$update instanceof UpdateInterface) {
            $this->logger->warning('unsupported update payload: ' . $update::class);
            return;
        }

        foreach ($this->handlers as $handler) {
            if ($handler->updateClass() === $update::class) {
                $handler->safeHandle($update);
                return;
            }
        }
        $this->logger->warning('no handler registered for ' . $update::class);
    }
}
