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

use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\MainBundle\Entity\User;
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 Chill\PersonBundle\Security\Authorization\PersonVoter;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;

class PersonDocumentVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
    final public const CREATE = 'CHILL_PERSON_DOCUMENT_CREATE';

    final public const DELETE = 'CHILL_PERSON_DOCUMENT_DELETE';

    final public const SEE = 'CHILL_PERSON_DOCUMENT_SEE';

    final public const SEE_DETAILS = 'CHILL_PERSON_DOCUMENT_SEE_DETAILS';

    final public const UPDATE = 'CHILL_PERSON_DOCUMENT_UPDATE';

    protected VoterHelperInterface $voterHelper;

    public function __construct(
        protected LoggerInterface $logger,
        protected Security $security,
        VoterHelperFactoryInterface $voterHelperFactory,
    ) {
        $this->voterHelper = $voterHelperFactory
            ->generate(self::class)
            ->addCheckFor(PersonDocument::class, $this->getRoles())
            ->addCheckFor(Person::class, [self::SEE, self::CREATE])
            ->build();
    }

    public function getRoles(): array
    {
        return [
            self::CREATE,
            self::SEE,
            self::SEE_DETAILS,
            self::UPDATE,
            self::DELETE,
        ];
    }

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

    public function getRolesWithoutScope(): array
    {
        return [];
    }

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

    /**
     * @param string         $attribute
     * @param PersonDocument $subject
     *
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $this->logger->debug(sprintf('Voting from %s class', self::class));

        if (!$token->getUser() instanceof User) {
            return false;
        }

        if (
            $subject instanceof PersonDocument
            && !$this->security->isGranted(PersonVoter::SEE, $subject->getPerson())
        ) {
            return false;
        }

        return $this->voterHelper->voteOnAttribute($attribute, $subject, $token);
    }
}
