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

use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;

/**
 * Class DuplicateEntityWorkflowFinder.
 *
 * Finds duplicate entity workflows based on their status.
 */
class DuplicateEntityWorkflowFinder
{
    public function __construct(private readonly EntityWorkflowRepository $entityWorkflowRepository, private readonly OpenedEntityWorkflowHelper $openedEntityWorkflowHelper) {}

    /**
     * Return true if the related entity has opened workflow with same name, or workflow with a positive final step.
     *
     * This will return false if the other workflow is final **and** negative (because it has been canceled, for instance).
     *
     * If there isn't any other workflow related to the same entity, this will return false.
     */
    public function hasDuplicateOpenedOrFinalPositiveEntityWorkflow(EntityWorkflow $entityWorkflow): bool
    {
        $otherWorkflows = $this->entityWorkflowRepository->findByRelatedEntity($entityWorkflow->getRelatedEntityClass(), $entityWorkflow->getRelatedEntityId());

        foreach ($otherWorkflows as $otherWorkflow) {
            if ($entityWorkflow === $otherWorkflow) {
                continue;
            }

            if ($otherWorkflow->getWorkflowName() !== $entityWorkflow->getWorkflowName()) {
                continue;
            }

            if (!$this->openedEntityWorkflowHelper->isFinal($otherWorkflow)) {
                return true;
            }

            if ($this->openedEntityWorkflowHelper->isFinalPositive($otherWorkflow)) {
                return true;
            }
        }

        return false;
    }
}
