<?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\Repository\Workflow;

use Chill\DocStoreBundle\Security\Authorization\StoredObjectRoleEnum;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowSignatureStateEnum;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Security\Core\Security;

class EntityWorkflowStepSignatureACLAwareRepository implements EntityWorkflowSignatureACLAwareRepositoryInterface
{
    public function __construct(
        private readonly EntityWorkflowStepSignatureRepository $repository,
        private readonly EntityWorkflowManager $entityWorkflowManager,
        private readonly Security $security,
    ) {}

    public function findByPersonAndPendingState(Person $person): array
    {
        $signatures = $this->repository->findByPerson($person);

        $filteredSignatures = [];

        foreach ($signatures as $signature) {
            if (EntityWorkflowSignatureStateEnum::SIGNED === $signature->getState() || EntityWorkflowSignatureStateEnum::CANCELED === $signature->getState() || EntityWorkflowSignatureStateEnum::REJECTED === $signature->getState()) {
                continue;
            }

            $workflow = $signature->getStep()->getEntityWorkflow();

            $storedObject = $this->entityWorkflowManager->getAssociatedStoredObject($workflow);

            if (null === $storedObject) {
                continue;
            }

            if ($this->security->isGranted(StoredObjectRoleEnum::SEE->value, $storedObject)) {
                $filteredSignatures[] = $signature;
            }
        }

        return $filteredSignatures;
    }
}
