<?php

namespace NoahVet\Reef\Security\IAM\Finder;

use NoahVet\Reef\Domain\Security\Port\ResourceFinderInterface;
use NoahVet\Reef\Domain\Security\Port\ResourceLocatorInterface;

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 ResourceLocatorInterface) {
                $ret = $resourceFinder->findBySlug($slug);

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

        return null;
    }
}
