<?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\Entity\Workflow\EntityWorkflowStep;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\WorkflowInterface;

class MetadataExtractor
{
    public function __construct(
        private readonly Registry $registry,
        private readonly TranslatableStringHelperInterface $translatableStringHelper,
        private readonly DuplicateEntityWorkflowFinder $duplicateEntityWorkflowFinder,
    ) {}

    /**
     * @return list<array{name: string, text: string}>
     */
    public function availableWorkflowFor(string $relatedEntityClass, ?int $relatedEntityId = 0): array
    {
        $blankEntityWorkflow = new EntityWorkflow();
        $blankEntityWorkflow
            ->setRelatedEntityId($relatedEntityId)
            ->setRelatedEntityClass($relatedEntityClass)
        ;

        // build the list of available workflows, and extract their names from metadata
        $workflows = $this->registry->all($blankEntityWorkflow);
        $workflowsList = [];

        foreach ($workflows as $workflow) {
            // shortcut: we must not be able to create a new workflow if there are already created workflows,
            // so, we find if there are workflows opened or final positive for the same entity
            $blankEntityWorkflow->setWorkflowName($workflow->getName());
            if ($this->duplicateEntityWorkflowFinder->hasDuplicateOpenedOrFinalPositiveEntityWorkflow($blankEntityWorkflow)) {
                // if yes, we skip suggesting workflow
                continue;
            }

            $metadata = $workflow->getMetadataStore()->getWorkflowMetadata();
            $text = \array_key_exists('label', $metadata) ?
                $this->translatableStringHelper->localize($metadata['label']) : $workflow->getName();

            $workflowsList[] = ['name' => $workflow->getName(), 'text' => $text];
        }

        return $workflowsList;
    }

    /**
     * @return array{name: string, text: string}
     */
    public function buildArrayPresentationForPlace(EntityWorkflow $entityWorkflow, ?EntityWorkflowStep $step = null): array
    {
        $workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());
        $step ??= $entityWorkflow->getCurrentStep();

        $markingMetadata = $workflow->getMetadataStore()->getPlaceMetadata($step->getCurrentStep());

        $text = \array_key_exists('label', $markingMetadata) ?
            $this->translatableStringHelper->localize($markingMetadata['label']) : $step->getCurrentStep();

        return ['name' => $step->getCurrentStep(), 'text' => $text];
    }

    /**
     * @return array{name?: string, text?: string, isForward?: bool}
     */
    public function buildArrayPresentationForTransition(EntityWorkflow $entityWorkflow, string $transitionName): array
    {
        $workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());
        $transitions = $workflow->getDefinition()->getTransitions();

        foreach ($transitions as $transition) {
            if ($transition->getName() === $transitionName) {
                $metadata = $workflow->getMetadataStore()->getTransitionMetadata($transition);

                return [
                    'name' => $transition->getName(),
                    'text' => \array_key_exists('label', $metadata) ?
                        $this->translatableStringHelper->localize($metadata['label']) : $transition->getName(),
                    'isForward' => $metadata['isForward'] ?? null,
                ];
            }
        }

        return [];
    }

    /**
     * @return array{name: string, text: string}
     */
    public function buildArrayPresentationForWorkflow(WorkflowInterface $workflow): array
    {
        $metadata = $workflow->getMetadataStore()->getWorkflowMetadata();
        $text = \array_key_exists('label', $metadata) ?
            $this->translatableStringHelper->localize($metadata['label']) : $workflow->getName();

        return ['name' => $workflow->getName(), 'text' => $text];
    }
}
