<?php

declare(strict_types=1);

namespace NoahVet\Reef\Security\IAM\Finder;

class ResourceFinderManager
{
    /**
     * @var array<ResourceFinderInterface>
     */
    protected array $resourceFinders;

    /**
     * @param iterable<ResourceFinderInterface> $resourceFinders
     */
    public function __construct(
        iterable $resourceFinders,
    ) {
        $this->resourceFinders = [];

        foreach ($resourceFinders as $resourceFinder) {
            $this->resourceFinders[] = $resourceFinder;
        }
    }

    public function createIterator(): ResourceIterator
    {
        return new ResourceIterator($this->resourceFinders);
    }

    public function findBySlug(string $slug): mixed
    {
        foreach ($this->resourceFinders as $resourceFinder) {
            if ($resourceFinder instanceof ReverseResourceFinderInterface) {
                $ret = $resourceFinder->findBySlug($slug);

                if (null !== $ret) {
                    return $ret;
                }
            }
        }

        return null;
    }
}
