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

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Security\Authorization\StoredObjectRoleEnum;
use Chill\DocStoreBundle\Security\Authorization\StoredObjectVoterInterface;
use Chill\MainBundle\Repository\ExportGenerationRepository;
use Chill\MainBundle\Security\Authorization\ExportGenerationVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;

final readonly class ExportGenerationStoredObjectVoter implements StoredObjectVoterInterface
{
    public function __construct(private ExportGenerationRepository $repository, private Security $security) {}

    public function supports(StoredObjectRoleEnum $attribute, StoredObject $subject): bool
    {
        return null !== $this->repository->findAssociatedEntityToStoredObject($subject);
    }

    public function voteOnAttribute(StoredObjectRoleEnum $attribute, StoredObject $subject, TokenInterface $token): bool
    {
        if (StoredObjectRoleEnum::EDIT === $attribute) {
            return false;
        }

        if (null === $generation = $this->repository->findAssociatedEntityToStoredObject($subject)) {
            throw new \UnexpectedValueException('generation not found');
        }

        return $this->security->isGranted(ExportGenerationVoter::VIEW, $generation);
    }
}
