<?php

declare(strict_types=1);

namespace Gls\GlsPoland\MessageHandler\Labels\Download;

final class DownloadLabelsHandlerChainFactory
{
    private $handlers;

    /**
     * @param iterable<DownloadLabelsHandlerInterface> $handlers
     */
    public function __construct(iterable $handlers)
    {
        $this->handlers = $handlers;
    }

    public function create(): ?DownloadLabelsHandlerInterface
    {
        $handlers = $this->handlers;
        if ($handlers instanceof \Traversable) {
            $handlers = iterator_to_array($handlers);
        }

        $first = $previous = array_shift($handlers);
        foreach ($handlers as $handler) {
            $previous->setNext($handler);
            $previous = $handler;
        }

        return $first;
    }
}
