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

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class PersonVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
    final public const CREATE = 'CHILL_PERSON_CREATE';

    final public const DUPLICATE = 'CHILL_PERSON_DUPLICATE';

    final public const LISTS = 'CHILL_PERSON_LISTS';

    final public const SEE = 'CHILL_PERSON_SEE';

    final public const STATS = 'CHILL_PERSON_STATS';

    final public const UPDATE = 'CHILL_PERSON_UPDATE';

    protected VoterHelperInterface $voter;

    public function __construct(
        VoterHelperFactoryInterface $voterFactory,
    ) {
        $this->voter = $voterFactory
            ->generate(self::class)
            ->addCheckFor(Center::class, [self::STATS, self::LISTS, self::DUPLICATE])
            ->addCheckFor(Person::class, [self::CREATE, self::UPDATE, self::SEE, self::DUPLICATE])
            ->addCheckFor(null, [self::CREATE])
            ->build();
    }

    public function getRoles(): array
    {
        return $this->getAttributes();
    }

    public function getRolesWithHierarchy(): array
    {
        return ['Person' => $this->getRoles()];
    }

    public function getRolesWithoutScope(): array
    {
        return $this->getAttributes();
    }

    protected function supports($attribute, $subject)
    {
        return $this->voter->supports($attribute, $subject);
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        return $this->voter->voteOnAttribute($attribute, $subject, $token);
    }

    private function getAttributes()
    {
        return [self::CREATE, self::UPDATE, self::SEE, self::STATS, self::LISTS, self::DUPLICATE];
    }
}
