<?php

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

use PublishPress\Future\Modules\Workflows\Domain\Steps\Actions\Definitions\DeletePostMeta;
use PublishPress\Future\Modules\Workflows\Interfaces\StepRunnerInterface;
use PublishPress\Future\Modules\Workflows\Interfaces\StepProcessorInterface;
use PublishPress\Future\Modules\Workflows\Interfaces\ExecutionContextInterface;

class DeletePostMetaRunner implements StepRunnerInterface
{
    /**
     * @var StepProcessorInterface
     */
    private $stepProcessor;

    /**
     * @var \Closure
     */
    private $expirablePostModelFactory;

    /**
     * @var ExecutionContextInterface
     */
    private $executionContext;

    public function __construct(
        StepProcessorInterface $stepProcessor,
        \Closure $expirablePostModelFactory,
        ExecutionContextInterface $executionContext
    ) {
        $this->stepProcessor = $stepProcessor;
        $this->expirablePostModelFactory = $expirablePostModelFactory;
        $this->executionContext = $executionContext;
    }

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

    public function setup(array $step): void
    {
        $this->stepProcessor->setup($step, [$this, 'actionCallback']);
    }

    public function actionCallback(int $postId, array $nodeSettings, array $step)
    {
        $this->stepProcessor->executeSafelyWithErrorHandling(
            $step,
            function ($step, $postId, $nodeSettings) {
                /** @var ExpirablePostModelInterface $postModel */
                $postModel = call_user_func($this->expirablePostModelFactory, $postId);

                $metaValue = $this->executionContext->resolveExpressionsInText(
                    $nodeSettings['metaValue']['expression']
                );

                if (empty($metaValue)) {
                    $metaValue = null;
                }

                $postModel->deleteMeta($nodeSettings['metaKey'], $metaValue);
            },
            $postId,
            $nodeSettings
        );
    }
}
