<?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\Authorization;

use Chill\MainBundle\Entity\User;

final readonly class DefaultVoterHelper implements VoterHelperInterface
{
    public function __construct(
        private AuthorizationHelper $authorizationHelper,
        private array $configuration,
    ) {}

    public function supports($attribute, $subject): bool
    {
        foreach ($this->configuration as [$attributes, $subj]) {
            if (null === $subj) {
                if (null === $subject && \in_array($attribute, $attributes, true)) {
                    return true;
                }
            } elseif ($subject instanceof $subj) {
                return \in_array($attribute, $attributes, true);
            }
        }

        return false;
    }

    public function voteOnAttribute($attribute, $subject, $token): bool
    {
        $user = $token->getUser();

        if (!$user instanceof User) {
            return false;
        }

        if (null === $subject) {
            return [] !== $this->authorizationHelper->getReachableCenters($token->getUser(), $attribute, null);
        }

        return $this->authorizationHelper->userHasAccess(
            $user,
            $subject,
            $attribute
        );
    }
}
