<?php

namespace NoahVet\Reef\Application\Security\Service;

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

/**
 * Application service for iterating and locating resources across all registered finders.
 * Replaces ResourceFinderManager for new-style dependency injection.
 */
class ResourceFinderService implements ResourceFinderServiceInterface
{
    /**
     * @var list<ResourceEnumeratorInterface|ResourceLocatorInterface>
     */
    private array $finders;

    /**
     * @param iterable<ResourceEnumeratorInterface|ResourceLocatorInterface> $finders
     */
    public function __construct(iterable $finders)
    {
        $this->finders = [];

        foreach ($finders as $finder) {
            $this->finders[] = $finder;
        }
    }

    /**
     * Yields all resources from all registered enumerators, sequentially.
     *
     * @return \Generator<mixed>
     */
    #[\Override]
    public function iterate(): \Generator
    {
        foreach ($this->finders as $finder) {
            if (!$finder instanceof ResourceEnumeratorInterface) {
                continue;
            }

            yield from $finder->enumerate();
        }
    }

    /**
     * Returns the first entity matching the given IAM slug across all registered locators.
     */
    #[\Override]
    public function findBySlug(string $slug): mixed
    {
        foreach ($this->finders as $finder) {
            if (!$finder instanceof ResourceLocatorInterface) {
                continue;
            }

            $ret = $finder->findBySlug($slug);

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

        return null;
    }
}
