<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Security\Resolver;

use Chill\MainBundle\Entity\Scope;
use Doctrine\Common\Collections\Collection;

final readonly class ScopeResolverDispatcher
{
    /**
     * @param ScopeResolverInterface[] $resolvers
     */
    public function __construct(private iterable $resolvers) {}

    public function isConcerned($entity, ?array $options = []): bool
    {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->supports($entity, $options)) {
                return $resolver->isConcerned($entity, $options);
            }
        }

        return false;
    }

    /**
     * @return Scope|iterable<Scope>|Scope|null
     */
    public function resolveScope(mixed $entity, ?array $options = []): iterable|Scope|null
    {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->supports($entity, $options)) {
                $scopes = $resolver->resolveScope($entity, $options);

                if ($scopes instanceof Collection) {
                    return $scopes->toArray();
                }

                return $scopes;
            }
        }

        return null;
    }
}
