<?php

namespace PublishPress\FuturePro\Modules\Workflows\Domain\Steps\Triggers\Runners;

use PublishPress\Future\Core\HookableInterface;
use PublishPress\Future\Modules\Workflows\Domain\Steps\Triggers\Definitions\OnInit;
use PublishPress\Future\Modules\Workflows\HooksAbstract as FreeHooksAbstract;
use PublishPress\Future\Modules\Workflows\Interfaces\StepProcessorInterface;
use PublishPress\Future\Modules\Workflows\Interfaces\TriggerRunnerInterface;
use PublishPress\FuturePro\Modules\Workflows\HooksAbstract;

class OnInitRunner implements TriggerRunnerInterface
{
    /**
     * @var HookableInterface
     */
    private $hooks;

    /**
     * @var array
     */
    private $step;

    /**
     * @var StepProcessorInterface
     */
    private $stepProcessor;

    /**
     * @var int
     */
    private $workflowId;

    public function __construct(
        HookableInterface $hooks,
        StepProcessorInterface $stepProcessor
    ) {
        $this->hooks = $hooks;
        $this->stepProcessor = $stepProcessor;
    }

    public static function getNodeTypeName(): string
    {
        return OnInit::getNodeTypeName();
    }

    public function setup(int $workflowId, array $step): void
    {
        $this->step = $step;
        $this->workflowId = $workflowId;

        $this->hooks->addAction(FreeHooksAbstract::ACTION_INIT, [$this, 'triggerCallback'], 13);
    }

    public function triggerCallback()
    {
        $this->stepProcessor->executeSafelyWithErrorHandling(
            $this->step,
            function ($step) {
                $this->stepProcessor->triggerCallbackIsRunning();

                $this->hooks->doAction(
                    HooksAbstract::ACTION_WORKFLOW_TRIGGER_EXECUTED,
                    $this->workflowId,
                    $this->step
                );

                $this->stepProcessor->runNextSteps($this->step);
            },
            $this->step
        );
    }
}
